Lambda方法总结

本文总结了Java 8中Lambda表达式与Stream API的常用收集方法,包括toList、toSet、toCollection、counting、summingInt、averagingInt、joining、maxBy、minBy、reducing、collectingAndThen、groupingBy和partitioningBy等,通过实例展示了如何在实际操作中使用这些方法进行数据处理和聚合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

toList                把流中所有元素收集到List中
示例:
Menu.getMenus.stream().collect(Collectors.toList())

toSet                把流中所有元素收集到Set中,删除重复项
示例:Menu.getMenus.stream().collect(Collectors.toSet())

toCollection         把流中所有元素收集到给定的供应源创建的集合中
示例:Menu.getMenus.stream().collect(Collectors.toCollection(ArrayList::new))

Counting        Long         计算流中元素个数
示例:Long count=Menu.getMenus.stream().collect(counting);

SummingInt         Integer         对流中元素的一个整数属性求和
示例:Integer count=Menu.getMenus.stream().collect(summingInt(Menu::getCalories))

averaging       Int Double 计算流中元素integer属性的平均值
示例:Double averaging=Menu.getMenus.stream().collect(averagingInt(Menu::getCalories))

Joining         String        连接流中每个元素的toString方法生成的字符串
示例:String name=Menu.getMenus.stream().map(Menu::getName).collect(joining(“, ”))

maxBy         Optional         一个包裹了流中按照给定比较器选出的最大元素的optional,如果为空返回的是Optional.empty()
示例:Optional fattest=Menu.getMenus.stream().collect(maxBy(Menu::getCalories))

minBy        Optional        一个包裹了流中按照给定比较器选出的最大元素的optional如果为空返回的是Optional.empty()
示例: Menu.getMenus.stream().collect(minBy(Menu::getCalories))

Reducing         归约操作产生的类型         从一个作为累加器的初始值开始,利用binaryOperator与流中的元素逐个结合,从而将流归约为单个值
示例:int count=Menu.getMenus.stream().collect(reducing(0,Menu::getCalories,Integer::sum));

collectingAndThen         转换函数返回的类型         包裹另一个转换器,对其结果应用转换函数
示例:Int count=Menu.getMenus.stream().collect(collectingAndThen(toList(),List::size))

groupingBy         Map<K,List>         根据流中元素的某个值对流中的元素进行分组,并将属性值做为结果map的键
示例:Menu.getMenus.stream().collect(groupingby(Menu::getType))

partitioningBy        Map<Boolean,List>         根据流中每个元素应用谓语的结果来对项目进行分区
示例: Menu.getMenus.stream().collect(partitioningBy(Menu::isType));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值