java8流處理
阿新 • • 發佈:2020-12-15
記一下java流處理的操作
1.去重,按照billTypeCode去重
list = list.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(o -> o.getBillTypeCode()))), ArrayList::new));
2.求和
Double sum = workDoc.getItemList().stream().mapToDouble(e -> e.getAllocatedQuantity().doubleValue()).reduce(0, Double::sum);
3.遍歷賦值
list.stream().forEach(e -> e.setStatus("30"));
4.過濾
List<ItemInfo> itemone = new ArrayList<>(itemInfos);
itemone = itemone.stream().filter(o -> matnr.equals(o.getItemCode())).collect(Collectors.toList());
5.map:stream().map()可以讓你轉化一個物件成其他的物件
List<String> lineList = itemCodeNoExistList.stream().map(ShopOrderExcelDto::getLine).collect(Collectors.toList());
6.把list轉化為map,key是id,value是實體,如果存在重複的key,取第一個實體
Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, Function.identity(),(k1, k2) -> k1));
7.取值去重
List<String> targetFactoryCode = targetLocationList.stream().map(Location::getFactoryCode).distinct().collect(Collectors.toList());
8.分組,對於list中的物件按照名字分組,返回一個map<String,List>
Map<String,List<Person>> m = list.stream().collect(Collectors.groupingBy(l->l.getName()));
9.分組,返回一個Map<Boolean,List>,如果分組了,就是list的size>1,則是true,否則是false
Map<Boolean,List<Person>> m = list.stream().collect(Collectors.groupingBy(p->p.getName().equals("haha")));
10.groupingBy()
提供第二個引數,表示downstream,即對分組後的value作進一步的處理,返回map<String,Set>
Map<String,Set<Person>> m = list.stream().collect(Collectors.groupingBy(l->l.getName(),Collectors.toSet()));
11.分組,返回value集合中元素的數量
Map<String,Long> m = list.stream().collect(Collectors.groupingBy(l->l.getName(),Collectors.counting()));
12.分組,對value集合中元素求和
Map<String,Integer> m = list.stream().collect(Collectors.groupingBy(l->l.getName(),Collectors.summingInt(Person::getId)));
13.分組,並取value集合中某個元素最大的實體,在這裡先按照name分組,然後取id最大的的實體,注意value是Optional的
Map<String,Optional<Person>> m = list.stream().collect(Collectors.groupingBy(l->l.getName(),Collectors.maxBy(Comparator.comparing(Person::getId))));
14.分組,並通過mapping對value欄位進行處理
Map<String,Set<Integer>> m = list.stream().collect(Collectors.groupingBy(l->l.getName(),Collectors.mapping(Person::getId,Collectors.toSet())));