@Data
@AllArgsConstructor
public class DailyDataChartVo {
/**
* 日期
*/
private LocalDate date;
/**
* 今日营收
*/
private BigDecimal revenue;
}
public static <T, K, U, M extends Map<K, U>>
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapSupplier) {}
??Collectors.toMap()一共有三个重载方法,前两个参数都是Function接口,分别用来指定生成key和value的策略;第三个参数用来指定当key重复时的操作,如果未指定,当key重复时,直接抛出异常;第四个参数用来指定生成Map的类型,默认创建的是HashMap。
Map<LocalDate, DailyDataChartVo> map = list.stream()
.collect(Collectors.toMap(DailyDataChartVo::getDate, Function.identity()));
Map<LocalDate, DailyDataChartVo> map = list.stream()
.collect(Collectors.toMap(DailyDataChartVo::getDate, Function.identity(), (c1, c2) -> c1));
Map<LocalDate, DailyDataChartVo> map = list.stream()
.collect(Collectors.toMap(DailyDataChartVo::getDate, Function.identity(), (c1, c2) -> c1, TreeMap::new));
public static <T, K> Collector<T, ?, Map<K, List<T>>>
groupingBy(Function<? super T, ? extends K> classifier) {
return groupingBy(classifier, toList());
}
public static <T, K, A, D>
Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
Collector<? super T, A, D> downstream) {
return groupingBy(classifier, HashMap::new, downstream);
}
??Collectors.groupingBy()也是三个重载方法,第一个参数是一个Function接口,用来指定分组的策略;第二个参数用来指定生成Map的类型,默认创建的是HashMap;第三个参数是一个收集器,指定对流中元素的收集策略。
Map<LocalDate, List<DailyDataChartVo>> map = list.stream()
.collect(Collectors.groupingBy(DailyDataChartVo::getDate));
Map<LocalDate, Long> map = list.stream()
.collect(Collectors.groupingBy(DailyDataChartVo::getDate, Collectors.counting()));
Map<LocalDate, List<BigDecimal>> map = list.stream()
.collect(Collectors.groupingBy(DailyDataChartVo::getDate,
Collectors.mapping(DailyDataChartVo::getRevenue, Collectors.toList())));
Map<LocalDate, BigDecimal> map = list.stream()
.collect(Collectors.groupingBy(DailyDataChartVo::getDate,
Collectors.mapping(DailyDataChartVo::getRevenue,
Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
Map<LocalDate, DailyDataChartVo> map = list.stream()
.collect(Collectors.groupingBy(DailyDataChartVo::getDate,
Collectors.collectingAndThen(Collectors.toList(), c -> c.get(0))));
LinkedHashMap<LocalDate, List<DailyDataChartVo>> map = list.stream()
.collect(Collectors.groupingBy(DailyDataChartVo::getDate, LinkedHashMap::new, Collectors.toList()));
原文:https://www.cnblogs.com/milete/p/14070775.html