lambda兰布达表达式

常用lambda表达式

1、中间操作(有状态)

// 去重(distinct) 	对象的话,需要重写equals方法
// 跳过(skip)	跳过前两个
List<Student> collect2 = students.stream().skip(2).collect(Collectors.toList());

// 截断(limit) 只取前2个
List<Student> collect2 = students.stream().limit(2).collect(Collectors.toList());

// 排序(sorted)
list.sort((o1, o2) -> o1.getId() - o2.getId());

 

2、终端操作(短路)

// 遍历(forEach)  lambda表达式 方法引用
list.forEach(System.out::println);

// 删除集合中的某个元素
lists.removeIf(ele -> ele.getId() == 7)

// 归约(reduce)
Optional<Double> op = emplyees.Stream()
            .map(Employee::getSalary)   // 获取到emplyees中的所有人的薪水(提取)
            .reduce(Double::sum);     // sum是Double中的一个静态方法,引用方法的形式代替lambda表达式。
System.out.println(op.get());  // 得到值


// 聚合(collect)
users.stream().collect(Collectors.groupingBy(User::getName))
        
// 根据名字分组:
Map<String, List<Student>> collect1 = students.stream().collect(Collectors.groupingBy(o -> o.getName()));

// 最大值(max)
// 先比较id,再比较年龄age
Student student = students.stream().max(Comparator.comparing(Student::getId).thenComparing(Student::getAge)).get();

// 最小值(min)
// 比较年龄,取最小值的对象:
Student student = students.stream().min(Comparator.comparing(Student::getAge)).get();
    
// 计数(count)  计算age=19的对象数
long count = students.stream().filter(o -> o.getAge() == 19).count();

// 遍历打印
answerList.stream().forEach(System.out::println);

 

3、终端操作(非短路)

// 所有匹配(allMatch) 是否所有人的名字都叫 '李四' :
boolean flag = students.stream().allMatch(o -> o.getName().equals("李四"));

// 任意匹配(anyMatch) 是否有人的年龄是19岁:
boolean b = students.stream().anyMatch(o -> o.getAge() == 19);

// 不匹配(noneMatch) 所有人年龄都不是100岁:
boolean b = students.stream().noneMatch(o -> o.getAge() == 100);

// 查找首个(findFirst)  查找第一个 
Optional<Student> any = students.stream().findFirst();

// 查找任意(findAny) 
// 使用findAny()是为了更高效的性能。如果是数据较少,串行地情况下,一般会返回第一个结果,如果是并行的情况,那就不能确保是第一个。
Optional<Student> any = students.stream().findAny();

 

4、中间操作(无状态)

// 过滤(filter) 取id为6的对象 
List<Student> collect = students.stream().filter(o -> o.getId() == 6).collect(Collectors.toList());

// 映射(map) 获取实体类对象中某一个字段转为List
List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());

// 扁平化(flatMap) FlatMap主要是用于stream合并,默认实现多CPU并行执行
// 将两个集合合并成一个集合 
List<Student> collect1 = Stream.of(students, collect).flatMap(Collection::stream).collect(Collectors.toList());

// 遍历(peek)  遍历集合(后面要用到才会遍历) 
List<Student> collect1 = students.stream().peek(o -> System.out.println("o = " + o)).collect(Collectors.toList());

 

posted @   得好好活  阅读(419)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示