reduce函数BigDecimal求和:
//list BigDecimal 求和 BigDecimal testBigDecimalValue = list.stream().map(a->a.get("key")).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); //int Integer testIntValue = list.stream().map(a->a.get("key")).reduce(Integer::sum).orElse(0);
summaryStatistics 获取 记录数 总和 均值 最大最小值:
List<Map<String,Integer>> list = new ArrayList<>(); Map<String,Integer> map = new HashMap(); map.put("key",300); list.add(map); //获取 记录数 总和 均值 最大最小值 list.stream().mapToInt((a)->a.get("key")).summaryStatistics().getCount(); list.stream().mapToInt((a)->a.get("key")).summaryStatistics().getSum(); list.stream().mapToInt((a)->a.get("key")).summaryStatistics().getAverage(); list.stream().mapToInt((a)->a.get("key")).summaryStatistics().getMax(); list.stream().mapToInt((a)->a.get("key")).summaryStatistics().getMin();
toList();
List list = Lists.stream().map(ceshiPojo::getId).collect(Collectors.toList());
list.sort 排序
//日期排序为例 List<String> dateList = dateMap.values().stream().collect(Collectors.toList()); dateList.sort((o1, o2) -> { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM"); YearMonth ym1 = YearMonth.parse(o1, dtf); YearMonth ym2 = YearMonth.parse(o2, dtf); return ym1.atEndOfMonth().compareTo(ym2.atEndOfMonth()); }); //stream.sorted List<Pojo> list = testList.stream().sorted(Comparator.comparing(Pojo::get排序字段)) .collect(Collectors.toList());
.filter() 过滤list
list.stream().filter(user -> user .getId() == null)
.distinct() 去重
Collectors.groupingBy()分组
Map<String, List<Pojo>> collects = list.stream().collect(Collectors.groupingBy(pojo::pojo.getKey()/*分组后的key*/));
list转map
//list转map userList.stream().collect(Collectors.toMap(User::getId, User::getName)); /* * Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, * Function<? super T, ? extends U> valueMapper) { * return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new); * } */ //参数 Function.identity() key:value 值是该对象本身 list.stream().collect(Collectors.toMap(pojo::getkey字段, Function.identity(), (o1, o2) -> o1));
Java9
挺详细的:Java 9 改进的 Stream API | 菜鸟教程
takeWhile() 方法在有序的 Stream 中,takeWhile 返回从开头开始的尽量多的元素;在无序的 Stream 中,takeWhile 返回从开头开始的符合 Predicate 要求的元素的子集
dropWhile 和 takeWhile相反
ofNullable 方法可以预防 NullPointerExceptions 异常