gpt4 book ai didi

java - lambda 和流 : collect in a Map

转载 作者:搜寻专家 更新时间:2023-10-31 19:51:55 24 4
gpt4 key购买 nike

我想使用 Stream 和 Lambda 组合构建一个 map 。

我尝试了很多方法,但还是卡住了。这是使用 Stream/Lambda 和经典循环来执行此操作的经典 Java 代码。

Map<Entity, List<Funder>> initMap = new HashMap<>();
List<Entity> entities = pprsToBeApproved.stream()
.map(fr -> fr.getBuyerIdentification().getBuyer().getEntity())
.distinct()
.collect(Collectors.toList());

for(Entity entity : entities) {
List<Funder> funders = pprsToBeApproved.stream()
.filter(fr -> fr.getBuyerIdentification().getBuyer().getEntity().equals(entity))
.map(fr -> fr.getDocuments().get(0).getFunder())
.distinct()
.collect(Collectors.toList());
initMap.put(entity, funders);
}

如您所见,我只知道如何在列表中进行收集,但我无法对 map 进行同样的操作。这就是为什么我必须再次流式传输我的列表以构建第二个列表,最后将所有列表放在 map 中。我也尝试过“collect.groupingBy”语句,因为它也应该生成 map ,但我失败了。

最佳答案

您似乎想将 pprsToBeApproved 列表中的任何内容映射到您的 Funder 实例,并按买家 Entity 对它们进行分组。

您可以按如下方式进行:

Map<Entity, List<Funder>> initMap = pprsToBeApproved.stream()
.collect(Collectors.groupingBy(
fr -> fr.getBuyerIdentification().getBuyer().getEntity(), // group by this
Collectors.mapping(
fr -> fr.getDocuments().get(0).getFunder(), // mapping each element to this
Collectors.toList()))); // and putting them in a list

如果您不希望某个特定实体有重复的资助者,您可以改为收集到一组 map :

Map<Entity, Set<Funder>> initMap = pprsToBeApproved.stream()
.collect(Collectors.groupingBy(
fr -> fr.getBuyerIdentification().getBuyer().getEntity(),
Collectors.mapping(
fr -> fr.getDocuments().get(0).getFunder(),
Collectors.toSet())));

这使用 Collectors.groupingByCollectors.mapping

关于java - lambda 和流 : collect in a Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741495/

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