我想我的问题从标题上可以很清楚。
我有两节课: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函数,我想使用它。
答案 0 :(得分:1)
您可能正在寻找Collectors.toMap
来收集B.id
和A
作为对象的地图
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"));