1 前言
Java8 出来的 stream 写法让我们对数据的处理带来了一些写法上的增进,这节就简单记录下平时使用的 stream 的一些操作,关于 stream 的书籍,可以看一下 Java8实战,里边会有两三章讲解我们的 stream。
2 常用记录
// 根据单个属性或者多个属性去重 List<Object> data = list.stream().collect(Collectors.collectingAndThen( Collectors.toCollection( () -> new TreeSet<>(Comparator.comparing(item -> item.getWarehouseCode() + item.getBusinessDate())) ), ArrayList::new )); // 多次分组 Map<String, Map<String, List<Object>>> data = list.stream().collect(Collectors.groupingBy(Object::getWarehouseCode, Collectors.groupingBy(Object::getRange))); // 分组后取第一条记录 Map<String, Object> data = list.stream().collect(Collectors.groupingBy(Object::getWarehouseCode, Collectors.collectingAndThen(Collectors.toList(), item -> item.get(0)))); // 分组后根据某个属性求和 int型 Map<String, Integer> data = list.stream().collect(Collectors.groupingBy(Object::getWarehouseCode, Collectors.summingInt(Object::getNum))); // 分组后根据某个属性求和 BigDecimal型 Map<String, BigDecimal> data = list.stream().collect(Collectors.groupingBy(Object::getWarehouseCode, Collectors.mapping(Object::getAvg, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)))); // 分组后收集某个属性的值 Map<String, List<String>> data = list.stream().collect(Collectors.groupingBy(Object::getWarehouseCode, Collectors.mapping(Object::getCode, Collectors.toList()))); Map<String, String> data = list.stream().collect(Collectors.groupingBy(Object::getWarehouseCode, Collectors.mapping(Object::getCode, Collectors.joining(",")))); // 分组后合并每个list List<Object> data = list.stream().collect(Collectors.groupingBy(Object::getWarehouseCode)) .values().stream().flatMap(Collection::stream).collect(Collectors.toList()); // 分组指定map类型 LinkedHashMap<String, List<Object>> data = list.stream().collect(Collectors.groupingBy(Object::getWarehouseCode, LinkedHashMap::new, Collectors.toList()));
加油
标签:Stream,Java,stream,Collectors,Object,list,collect,日常,getWarehouseCode From: https://www.cnblogs.com/kukuxjx/p/17207178.html