Java 8 Streams按功能分组,将嵌套对象的变量设置为键,并将父对象设置为值

时间:2018-09-18 08:31:41

标签: java collections java-8 hashmap java-stream

我想我的问题从标题上可以很清楚。

我有两节课:parent A and child B. 并希望像Map<Integer,A>这样的回报,其中key is a field from child B。 我从数据库中提取了List<A> aList。 类定义:

public class B {
    Integer id;
    String some;
    String some2;
}

public class A {
    Integer id;
    B someB;
    String name;
}

我尝试像aList.streams.collect(Collectors.groupingBy(A::getSomeB))一样,但这不是我想要的。 父母与子女之间只有一对一的关系,所以我不需要Map<Integer,List<A>> as the result

我可以通过循环aList来做到这一点,但是如果有内置的Java 8函数,我想使用它。

2 个答案:

答案 0 :(得分:1)

您可能正在寻找Collectors.toMap来收集B.idA作为对象的地图

Map<Integer, A> result = aList.stream().collect(
              Collectors.toMap(a -> a.getSomeB().getId(), Function.identity());

答案 1 :(得分:1)

在这种琐碎的情况下,您甚至不需要流:

Map<Integer, A> map = new HasMap<>();
aList.forEach(x -> map.merge(x.getSomeB().getId(), x, (oldV, newV) -> throw new AssertionError("must never happen"));