Flat-Mapping Collector for property of a Class using groupingBy(使用 groupingBy 的类属性的平面映射收集器)
问题描述
I have this class.
class Assignment {
private Integer index;
private List<Quantity> quantities;
}
Then, I have a list of objects from that class.
List<Assigment> assignments = new ArrayList<>();
Is there a way to create a Map
that contains the index from Assignment
and the List<Quantity>
as values?
This is what I have tried so far.
assignments.stream().collect(groupingBy(Assignment::getIndex));
But this gives me a Map<Integer, List<Assignment>>
and I want a Map<Integer, List<Quantity>>
.
I have tried using forEach
method - and it workes - but I'm sure there must be a way to do it in one liner - or at least using only collect
and groupingBy
methods
It looks like there is no flat-mapping collector that you can use as a down-stream for groupingBy
in Java8, but it has been proposed and accepted for Java9: https://bugs.openjdk.java.net/browse/JDK-8071600
public static <T, U, A, R>
Collector<T, ?, R> flatMapping(Function<? super T, ? extends Stream<? extends U>> mapper,
Collector<? super U, A, R> downstream) {
BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
return Collector.of(downstream.supplier(),
(r, t) -> mapper.apply(t).sequential().forEach(u -> downstreamAccumulator.accept(r, u)),
downstream.combiner(),
downstream.finisher(),
downstream.characteristics().stream().toArray(Collector.Characteristics[]::new));
}
If you use that one, and also add a quantities
method to Assignment
that returns a Stream<Quantity>
, you can use this code:
Map<Integer, List<Quantity>> result = assignments.stream()
.collect(groupingBy(Assignment::getIndex,
flatMapping(Assignment::quantities, toList())));
这篇关于使用 groupingBy 的类属性的平面映射收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 groupingBy 的类属性的平面映射收集器
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01