使用groupingBy的类的属性的平面映射收集器 [英] Flat-Mapping Collector for property of a Class using groupingBy
问题描述
我有这个课。
class Assignment {
private Integer index;
private List<Quantity> quantities;
}
然后,我有一个来自该类的对象列表。
Then, I have a list of objects from that class.
List<Assigment> assignments = new ArrayList<>();
有没有办法创建地图
包含来自分配
的索引和列表< Quantity>
作为值?
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));
但是这给了我一个 Map< Integer,List< Assignment>>
我想要一个 Map< Integer,List< Quantity>>
。
But this gives me a Map<Integer, List<Assignment>>
and I want a Map<Integer, List<Quantity>>
.
我已经尝试使用 forEach
方法 - 并且它可以工作 - 但我确信必须有一种方法可以在一个班轮中完成 - 或者至少只使用收集
和 groupingBy
方法
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
推荐答案
看起来没有平面映射收集器可以在Java8中用作 groupingBy
的下游,但Java9已经提出并接受了它: https://bugs.openjdk.java.net/browse/JDK-8071600
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));
}
如果使用那个,并将数量
方法添加到作业
,返回 Stream< Quantity>
,您可以使用以下代码:
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的类的属性的平面映射收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!