作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想使用 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.groupingBy
和 Collectors.mapping
。
关于java - lambda 和流 : collect in a Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741495/
我是一名优秀的程序员,十分优秀!