java8 stream 常见例子

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

前言

java8 stream提供了常规操作,可以简化编程,提高效率,我把自己常用的例子归纳下来

代码示例

代码如下(示例):

//list字符串逗号拼接
String str=strList.stream().collect(Collectors.joining(","));
//list按照属性过滤
List<User> first = users.stream().filter(e -> e.getLevel().equals("1")).collect(Collectors.toList());
//list过滤指定属性
List<Long> ids = userlist.stream().map(e -> e.getId()).collect(Collectors.toList());
//list属性求和
BigDecimal partListPrice = list.stream().filter(e -> e.getPrice() != null).map(PartRepository::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//list属性分组
Map<Long, List<User>>=.stream().collect(Collectors.groupingBy(User::getAge));
//去重
List<String> codes = strList.stream().distinct().collect(Collectors.toList());
//list分组
Map<Long, Catalog> catalogMap = catalogList.stream().collect(Collectors.toMap(Catalog::getId, Catalog -> Catalog));
//list转map
Map<String, Long> returnListMap = orderlist.stream().collect(Collectors.toMap(Order::getDate, Order::getTotal));
//查询第一个
NetworkClient first = networkClientList.stream().findFirst().orElse(null);
		if (first!=null) {
			
		}
//排序并取top		
List<BusContainer> =busContainerList.stream().sorted(Comparator.comparing(BusContainer::getEnterTime)).limit(10).collect(Collectors.toList());
//排除
if (CollectionUtils.isNotEmpty(extIds)) {
	busContainerList.removeIf(item -> extIds.contains(item.getId()));
}
//计数
long iosfc= orderList.stream().count();
//求和
long iosAmount = orderList.stream().mapToLong(o->o.getMoney()).sum();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值