lambda表达式运用 ----demo

发布时间 2023-05-09 17:30:45作者: 我的心儿
点击查看代码
public class test {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(21L, "张三"));
        list.add(new User(25L, "李四"));
        list.add(new User(22L, "王五"));
        list.add(new User(19L, "赵柳"));
        list.add(new User(32L, "王5"));
        list.add(new User(29L, "王6"));
        list.add(new User(21L, "王7"));
        list.add(new User(21L, "王7"));
       // list.forEach(System.out::println);
       List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
       List<User> newList1 = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
        newList.forEach(
                s->System.out.println("姓名:"  +  s.getName())
        );
        newList1.forEach(
                s->System.out.println("姓名:"  +  s.getName())
        );
        // 提取对象属性生成list
        List<Long> ids = list.stream().map(User::getAge).collect(Collectors.toList());
        System.out.println(ids);
        // list升序排序
        Collections.sort(ids);
        System.out.println(ids);

        List<User> newList2 = list.stream().filter(o->!o.getAge().equals(32L)).collect(Collectors.toList());
        newList2.forEach(o->System.out.println(o.getAge()));
        System.out.println("-----------------------------------------");
         list = list.stream().distinct().collect(Collectors.toList());
         list.forEach(User->System.out.print(User));
        System.out.println("-----------------------------------------");
        list.stream().distinct().forEach(System.out::println);

        System.out.println("-----------------------------------------");
        List<String> list2 = Arrays.asList("Geeks", "for", "Geeks",
                "GeeksQuiz", "for", "GeeksforGeeks","GeeksforGeeks");
        list2.stream().distinct().forEach(System.out::println);
    }
点击查看代码
package cn.tencent.data.ext.vo;

public class User {
    private Long age;

    /**
     *不同产品对应不同eventCode
     */
    private String name;
    public User(Long age, String name) {
        this.age = age;
        this.name = name;
    }
    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


}