【问题标题】:Lambda & Stream : collect in a MapLambda & Stream : 在地图中收集
【发布时间】:2018-10-10 13:35:14
【问题描述】:

我想使用 Stream 和 Lambda 组合构建地图。

我尝试了很多方法,但我被卡住了。这是使用 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);
        }

如您所见,我只知道如何在列表中收集,但我不能用地图做同样的事情。这就是为什么我必须再次流式传输我的列表以构建第二个列表,最后将所有内容放在一张地图中。 我也尝试过 'collect.groupingBy' 语句,因为它也应该生成地图,但我失败了。

【问题讨论】:

标签: java lambda java-8 hashmap java-stream


【解决方案1】:

您似乎想将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<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

【讨论】:

  • 只是为了我的回答是完整的: - 第一个 sn-p 工作但重复数据,什么对我不利,因为我想对条目进行分组 - 第二个 sn-p 很好,给了我我用我糟糕的代码达到了同样的结果。还有一件事:在这两种情况下,我必须用 Object 替换我使用的真实对象(Entity 和 Funder): Map> initMap =... 我不明白为什么。铸造我自己的课程不起作用。我还发现我对 Set 对象并不放心。我真的从不使用它,也许是因为我不知道它到底有什么用处。
  • 我知道@Eugene,我只是在写我的答案。没有压力^^
  • @Lovegiver Set 是一个不允许重复的集合。至于Map&lt;Object, Set&lt;Object&gt;&gt; initMap = ...,我不明白为什么编译器没有推断出正确的类型。 fr.getBuyerIdentification().getBuyer().getEntity() 是否返回 Entity 类型的对象? fr.getDocuments().get(0).getFunder() 是否返回 Funder 类型的对象?如果两者都是,那么你应该没有任何问题。
  • 该死的你是对的@Federico! fr.getDocuments().get(0).getFunder() 返回一个资助者,但 fr.getBuyerIdentification().getBuyer().getEntity() 只返回一个带有实体名称的字符串。我不知道为什么这两个对象之间的绑定是这样的(一个字符串,而不是类本身)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
  • 2016-11-10
  • 2016-12-27
  • 2010-10-16
  • 1970-01-01
相关资源
最近更新 更多