gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:55:22 31 4
gpt4 key购买 nike

我认为我的问题从标题中已经很清楚了。

我有两个类(class):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))但这不是我想要的。 parent 和 child 之间只有一对一的关系,所以我不需要 Map<Integer,List<A>> as the result

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

最佳答案

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

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

关于Java 8 Streams 按函数分组,将嵌套对象的变量设置为键,将父对象设置为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52382239/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com