gpt4 book ai didi

java - 使用 Collectors.toMap 或 groupingBy 在 Map 中收集映射操作的结果

转载 作者:行者123 更新时间:2023-12-02 09:18:18 25 4
gpt4 key购买 nike

我有一个类型为 List<A> 的列表并通过 map 操作获取 List<B> 类型的集体列表对于合并在一个列表中的所有 A 元素。

List<A> listofA = [A1, A2, A3, A4, A5, ...]

List<B> listofB = listofA.stream()
.map(a -> repo.getListofB(a))
.flatMap(Collection::stream)
.collect(Collectors.toList());

没有平面图

List<List<B>> listOflistofB = listofA.stream()
.map(a -> repo.getListofB(a))
.collect(Collectors.toList());

我想将结果收集为 Map<A, List<B>> 类型的 map 到目前为止尝试各种 Collectors.toMapCollectors.groupingBy选项,但无法获得所需的结果。

最佳答案

您可以将 toMap 收集器与有界方法引用结合使用来获取您需要的内容。另请注意,此解决方案假设您的源容器中没有重复的 A 实例。如果该前提条件成立,则该解决方案将为您提供所需的结果。这是它的样子。

Map<A, Collection<B>> resultMap = listofA.stream()
.collect(Collectors.toMap(Function.identity(), repo::getListofB);

如果您有重复的 A 元素,那么除了上面给出的功能之外,您还必须使用此合并功能。合并功能会处理关键冲突(如果有)。

Map<A, Collection<B>> resultMap = listofA.stream()
.collect(Collectors.toMap(Function.identity(), repo::getListofB,
(a, b) -> {
a.addAll(b);
return a;
}));

这里有一个更简洁的 Java9 方法,它使用 flatMapping 收集器来处理重复的 A 元素。

Map<A, List<B>> aToBmap = listofA.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.flatMapping(a -> getListofB(a).stream(),
Collectors.toList())));

关于java - 使用 Collectors.toMap 或 groupingBy 在 Map 中收集映射操作的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58203884/

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