今天被公司某人代码惊艳到,用到了听说过没见过的流处理。先贴代码
需求是计算一个LIST集合里某个属性的和
List<MonthDonateDetail> details = monthDonateDetail.selectByExample(..);
if(null != details && detail.size()>0){
return details.stream().map(MonthDonateDetail :: getmount).reduce(BigDeciaml.ZERO,BigDeciaml :: add)
} else {
return BigDeciaml.ZERO;
}
流好处:
1.简化集合类的处理
2.避免jvm装箱操作所带来的性能消耗。
具体用法:
https://www.cnblogs.com/shenlanzhizun/p/6027042.html
================2019-09-11 15:29:20=============
自初次使用了解已个半个月了,真的是一入流处深似海,越用越爽,带给我最直观的好处就是节省了好多行代码(如list按照某属性去重,过滤,排序、两个list<Object>按照某属性取交并补),总之,妈妈再也不用担心写代码写道手断了。
使用场景总结下,典型的例子如下:
LIST<Object> donar 1 //LIST简单的对象去重复
2 list = donarList.stream() .distinct () .collect (Collectors.toList ()); 3 //捐赠的项目按照项目id去重 4 idonarList = donarList 1.stream() . filter (distinctByKey {b->b.getProjid())) .collect (Collectors.toList ()); 5 //3 去除attachment属性为空的对象 6 List<ProjectInfoBto> simlist2 = simlist 1.stream() .filter (e->e.getAttachmentPath() != null) .collect (Collectors.toList ()); 7 //4•两个list,踢出simlist2中与卜xtlist含有相同项目id的印象 _ 8 liist<ProjectInf〇Bto> simlistf = simlist2.stream(). filter (item -> !extlist.stream() 9 .map(e -> e.getProj id()) 10 .collect(Collectors.toList()) 11 .contains (item.getProjidO )) .collect (Collectors.toList ()); 12 //jS.groupPeopleList - dbaGroupPeoples差集(groupid和account同时相等),这个是网上看到的帖子,忘记那篇了 13 List<XGroupPeople> distinctByUniqueList = groupPeopleList.stream. 14 .filter(item -> !dbaGroupPeoples.stream() 15 .map(e -> e. getAccount () + e. getGroupId ()) 16 .collect(Collectors.toList()) 17 .contains (item.getAccount () + item.getGroupIdO )) 18 //去重 19 .filter (UniqueUtils.distinctByKey (e -> e. getAccount ())) 20 .peek(e -> e.setId(UDIDUtil.uuid())) 21 .collect(Collectors.toList()); 22 //6.filter里可以放&,丨等条件一次过滤 53 private static <T> Predicate<T> distinctByKey (Function<? super T ,? > keyExtractor) { 55 Map<〇bject,Boolean> seen = new ConcurrentHashMapo(); 56 return t: -> seen.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE)==null;
}
吐槽下:公司不许连公网,写个博客我太难了