Java lambda 表达式常用示例

  1. 实体类
package com.lkb.java_lambda.dto;

import lombok.Data;

/**
 * @program: java_lambda
 * @description: dto
 * @author: lkb
 * @create: 2020-01-19 17:15
 */
@Data
public class Person implements Comparable<Person>{

    public Person(){}

    public Person(int id, String name, int age, String addr, int gender, double salary,String remark){
        this.id = id;
        this.age = age;
        this.name = name;
        this.addr = addr;
        this.gender = gender;
        this.salary = salary;
        this.remark = remark;
    }

    public Person(Person person) {
        this.id = person.id;
        this.name = person.name;
        this.age = person.age;
        this.addr = person.addr;
        this.gender = person.gender;
        this.salary = person.salary;
        this.remark = person.remark;
    }

    @Override
    public int compareTo(Person o) {
        if(this.salary > o.getSalary()){
            return 1;
        }else{
            return -1;
        }
    }

    private int id;
    private String name;
    private int age;
    private String addr;
    /**
     * 0-女 1-男
     */
    private int gender;
    private double salary;
    private String remark;
}
  1. 测试类
package com.lkb.java_lambda;

import cn.hutool.json.JSONUtil;
import com.lkb.java_lambda.dto.Person;

import java.awt.print.Book;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @program: java_lambda
 * @description: 测试类
 * @author: lkb
 * @create: 2020-01-19 17:18
 */
public class Test {

    private static List<Person> personList = new LinkedList<>();
    private static void init(){
        Person person = new Person();
        person.setId(1);
        person.setName("Lisa");
        person.setGender(0);
        person.setAge(24);
        person.setAddr("中国深圳");
        person.setSalary(15000d);
        personList.add(person);
        person = new Person();
        person.setId(2);
        person.setName("Tom");
        person.setGender(1);
        person.setAge(27);
        person.setAddr("中国深圳");
        person.setSalary(18000d);
        personList.add(person);
        person = new Person();
        person.setId(3);
        person.setName("Benny");
        person.setGender(1);
        person.setAge(22);
        person.setAddr("中国北京");
        person.setSalary(22000d);
        personList.add(person);
        person = new Person();
        person.setId(4);
        person.setName("Jenny");
        person.setGender(0);
        person.setAge(29);
        person.setAddr("中国上海");
        person.setSalary(33000d);
        personList.add(person);
        person = new Person();
        person.setId(5);
        person.setName("David");
        person.setGender(1);
        person.setAge(37);
        person.setAddr("中国北京");
        person.setSalary(22000d);
        personList.add(person);
    }


    public static void main(String[] args) {
        init();
        //List -> Map key是list中对象某一个段,value是整个对象
        //(key1,key2)->key1 是为了避免重复key(重复key会抛出异常)
        Map<Integer,Person> map = personList.stream().collect(Collectors.toMap(Person::getId, person -> person,(key1, key2)->key1));
        System.out.println(JSONUtil.toJsonStr(map));

        //List -> Map key是list中对象某一个段,value是某个字段
        Map<Integer,String> nameMap = personList.stream().collect(Collectors.toMap(Person::getId, person -> person.getName(),(key1, key2)->key1));
        System.out.println(JSONUtil.toJsonStr(nameMap));

        //list遍历
        personList.stream().forEach(p-> System.out.println(p.getName()));

        //根据某一条件过滤
        List<Person> personList1 = personList.stream().filter(p->p.getSalary()<20000d).collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(personList1));

        //根据多个条件过滤
        List<Person> personList2 = personList.stream().filter(p->p.getSalary()<20000d && p.getGender() == 1).collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(personList2));

        //根据多个条件过滤
        Predicate<Person> predicate1 = p->p.getSalary()<20000d;
        Predicate<Person> predicate2 = p-> p.getAddr().equals("中国深圳");
        List<Person> personList3 = personList.stream().filter(predicate1.and(predicate2)).collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(personList3));

        //去除重复的数据
        Person person = new Person();
        person.setId(5);
        person.setName("David");
        person.setGender(1);
        person.setAge(37);
        person.setAddr("中国北京");
        person.setSalary(22000d);
        personList.add(person);
        List<Person> personList4 = personList.stream().distinct().collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(personList4));

        //copy list
        personList = personList4.stream().map(Person::new).collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(personList));

        //根据某一条件去重
        List<Person> personList5 = personList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(
                                ()->new TreeSet<>(Comparator.comparing(Person::getAddr))),ArrayList::new));
        System.out.println(JSONUtil.toJsonStr(personList5));

        //取list中某个字段组成新的list
        List<String> names = personList.stream().map(Person::getName).collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(names));

        //返回满足条件的数量
        long num = personList.stream().filter(p->p.getAddr().equals("中国北京")).filter(p->p.getSalary() > 20000d).count();
        System.out.println("num = " + num);

        //按条件过滤,没有符合的返回给定值
        Person per = personList.stream().filter(p->p.getSalary()>50000d).findAny().orElse(null);
        if(Objects.isNull(per)){
            System.out.println("没有找到符合条件的person");
        }

        //查找第一个符合条件的数据
        Person per2 = personList.stream().filter((p->p.getSalary()>20000d)).findFirst().orElse(null);
        if(Objects.nonNull(per2)){
            System.out.println("第一个符合条件的人物是 " + JSONUtil.toJsonStr(per2));
        }

        //按照某个条件排序
        //默认按照自然排序
        List<Person> personList6 = personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(personList6));

        //自定义比较项目 然后进行排序
        //Person 类实现 Comparable 接口 重写compareTo方法  1-升序 -1-降序
        //这里我定义了按照salary升序排列
        List<Person> personList7 = personList.stream().sorted().collect(Collectors.toList());;
        System.out.println(JSONUtil.toJsonStr(personList7));

        //遍历处理
        personList.stream().forEach(p-> {
            if(p.getAddr().equals("中国北京")){
                p.setRemark("北京人");
            }
        });
        System.out.println(JSONUtil.toJsonStr(personList));

    }
}

最近看外国小哥的一个lambda视频觉得讲得很好,大家是可以看看,这个视频

个人总结一下:
Java 是面向对象,但有的时候面向过程、动作会更加轻量级一点,
所以Java lambda 就是将动作作为参数,再重量级的面向对象参杂一些面向过程的tools帮助我们更快捷地实现功能,更优雅地编程。

不知道上诉总结对不对,目前看来非常符合我在项目中使用lambda表达式的场景。

上一篇:java封神之路-stream流-进阶


下一篇:Codeforces Round #237 (Div. 2)