一、list 取单一字段 转targetList List targetList = list.stream().map(WeekDuty::getId).collect(Collectors.toList())
二、list 取指定字段 转targetMap Map<Long,Test> targetMap = list.stream().collect(Collectors.toMap(Test::getId,test -> test)); Map<Long,String> targetMap = list.stream().collect(Collectors.toMap(Test::getId,test -> test.getName));
三、list 分组 转 targetMap
//按对象分组 Map<Long, List<Test>> targetMap= list.stream().collect(Collectors.groupingBy(Test::getId)); //逗号组合姓名字符串 Map<Long,String> targetMap= list.stream().collect(Collectors.groupingBy(Test::getId, Collectors.mapping(Test::getName, Collectors.joining(","))));四、list 过滤 转 targetList
//过滤id大于10的 List<Test> targetList = list.stream().filter(a -> a.getId() > 10).collect(Collectors.toList());五、汇总 计算 //list 求和 转 sumAge int sumAge = list.stream().mapToInt(Test::getAge).sum(); //list 求最小日期 minEntryDate Date minEntryDate = list.stream().map(Test::getEntryDate).min(Date::compareTo).get(); //list 求最大日期 maxEntryDate Date maxEntryDate = userList.stream().map(Test::getEntryDate).max(Date::compareTo).get(); 六、排序 //单字段排序,根据id排序 targetList targetList = list.sort(Comparator.comparingTest::getId)); //多字段排序,根据id,年龄排序 targetList = list.sort(Comparator.comparing(User::getId).thenComparing(User::getAge)); 七、去重 List distinctIdList = list.stream().distinct().collect(Collectors.toList());
List<Test> distinctIdList = list.stream().filter(distinctByKey(b -> b.getId())).collect(Collectors.toList()); 自己定义 distinctByKey函数 public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }八、不同实体的list拷贝
List test1List = list.stream().map(p->{Test1 e = new Test1(); e.setIp(p.geId()); e.setEndDate(p.getEnd()); return e;}).collect(Collectors.toList()); 总结: parallelstream和stream使用方式基本相同,但使用场景不一样; parallelstream需要注意线程安全的问题。