List.steam()的强大之处在此不做赘述。
直接进入主题:
1.过滤Bean List中,某些字段等于指定值的所有行
List<Member> list = itemsArray.toJavaList(Member.class); List<String> roleList = new ArrayList<>(); roleList.add(roleName); List<Member> filterResult = list.stream().filter((Member m)->roleList.contains(m.getProjectRole())).collect(Collectors.toList());
2.判断Bean List中,是否存在某个属性的值等于指定的值
//方式1.直接使用lamda表达式判断filterResult中是否包含personEmail,推荐此方法 if (filterResult.stream().filter(w->String.valueOf(w.getPersonEmail()).equals(personEmail)).findAny().isPresent()){ log.info("filterResult包含"+personEmail); } //方式2,在过滤的结果基础上,对值为personEmail的行再生成一个List List<String> personEmailList = new ArrayList<>(); personEmailList.add(personEmail); List<Member> emailResult = filterResult.stream().filter((Member mem)->personEmailList.contains(mem.getPersonEmail())).collect(Collectors.toList()); log.info(emailResult.size()+"过滤后是否包含"+personEmail);
3.将Bean List中,指定属性的列的所有值转换成Set(Set特性,已去重)
Set<Long> result = list.stream().map(siteAssign->siteAssign.getVENDOR_ID()).collect(Collectors.toSet());
4.将Bean List中,指定属性的列的所有值转换成LIst(未去重)
List<Long> result = list.stream().map(siteAssign->siteAssign.getVENDOR_ID()).collect(Collectors.toList());
5.根据Bean List中的指定属性进行Distinct ,这样得到的行是一个完整的行,取表中VENDOR_ID相同的行中的任一行。
//https://blog.csdn.net/weixin_30451709/article/details/96156020 //通过treeset去重,获取非员工供应商中的所有供应商ID,不重复 List<SuppSiteAssign> result1 = siteAssignList.stream().filter(w -> !"EMPLOYEE".equals(w.getVENDOR_TYPE_LOOKUP_CODE())).collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SuppSiteAssign::getVENDOR_ID))), ArrayList::new)); //同上,由其他方法完成 List<SuppSiteAssign> result2= siteAssignList.parallelStream().filter(StreamUtil.distinctByKey(SuppSiteAssign::getVENDOR_ID)).collect(Collectors.toList()); StreamUtil public class StreamUtil { /** * https://stackoverflow.com/questions/23699371/java-8-distinct-by-property * https://www.cnblogs.com/woshimrf/p/java-list-distinct.html * @return */ public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Set<Object> seen = ConcurrentHashMap.newKeySet(); return t -> seen.add(keyExtractor.apply(t)); } }
关于parallelStream(),我尚未理解清楚。具体待查证。
6.既然有distinct方法,就必然有group by方法
https://blog.csdn.net/u013218587/article/details/74600585
//按用户,role分组求数量 Map<String, Map<String, Long>> tradeNumMap = dataAccessBeans.stream().collect(Collectors.groupingBy(DataAccessBean::getUSERNAME, Collectors.groupingBy(DataAccessBean::getROLE_NAME_DISPLAY, Collectors.counting()))); for(String userName : tradeNumMap.keySet()){ Map<String, Long> map = tradeNumMap.get(userName); for(String roleName : map.keySet()){ Long count = map.get(roleName); if(count>10){ log.info(userName+"-"+roleName+"-"+count); } } }