使用forEach,Java 8创建List列表(嵌套列表) [英] stream creating List of List (nested List) using forEach, Java 8

查看:1000
本文介绍了使用forEach,Java 8创建List列表(嵌套列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class EntityCompositeId {
    private Long firstId;
    private Long secondId;
    // getter & setter...
}

class EntityComposite {
    private EntityCompositeId id;
    private String first;
    private String second;
    // getter & setter...
}

List<EntityComposite> listEntityComposite = ....
Supose this content

1, 1, "firstA", "secondBirdOne"
1, 2, "firstA", "secondBirdTwo"
1, 3, "firstA", "secondBirdThree"

2, 1, "firstB", "secondCatOne"
2, 2, "firstB", "secondCatTwo"
2, 3, "firstB", "secondCatThree"

3, 1, "firstC", "secondDogOne"
3, 2, "firstC", "secondDogTwo"
3, 3, "firstC", "secondDogThree"

Map<Long, List<String>> listOfLists = new HashMap<>();

现在使用流我希望填写如下:

Now using stream I want to fill like:

 1 -> {"secondBirdOne", "secondBirdTwo", "secondBirdThree"}
 2 -> {"secondCatOne", "secondCatTwo", "secondCatThree"}
 3 -> {"secondDogOne", "secondDogTwo", "secondDogThree"}

我的UNFINISHED(这是问题)代码是:

My UNFINISHED (that's the question) code is:

listEntityComposite.stream()forEach(entityComposite {
        // How create a list according entityComposite.getId.getFirstId()?
        listOfLists.put(entityComposite.getId.getFirstId(), .... )
    });


推荐答案

有几种不同的方法可以让你完成手头的任务。

There are several different approaches in which you can accomplish the task at hand.

forEach + computeIfAbsent

 Map<Long, List<String>> map = new HashMap<>();
 listEntityComposite.forEach(e -> map.computeIfAbsent(e.getId().getFirstId(), 
                k -> new ArrayList<>()).add(e.getSecond()));




  • 枚举 listEntityComposite中的元素通过 forEach

  • 每个元素使用 computeIfAbsent 到计算密钥(即 firstId )和值(即 List< String>

    • enumerates over the elements in listEntityComposite via forEach
    • for each element utilises computeIfAbsent to compute the key (i.e. firstId) and value (i.e. List<String>)
    • groupingBy + mapping

      另一种方法是使用映射下游收集器应用 groupingBy

      another approach would be to apply a groupingBy with a mapping downstream collector:

      Map<Long, List<String>> resultSet = listEntityComposite.stream()
                      .collect(groupingBy(e -> e.getId().getFirstId(),
                              mapping(EntityComposite::getSecond, toList())));
      




      • 按分类函数对源元素进行分组 e.getId()。getFirstId()然后应用映射下游收集器以进一步优化我们的查询。

        • groups the source elements by the classification function e.getId().getFirstId() and then applies a mapping downstream collector to further refine our query.
        • forEach + merge

          listEntityComposite.forEach(e -> map.merge(e.getId().getFirstId(),
                          new ArrayList<>(singletonList(e.getSecond())),
                          (l, r) -> {l.addAll(r); return l;}));
          




          • 枚举中的元素listEntityComposite via forEach

            每个元素使用 merge 来计算密钥(即 firstId )和值(即 List< String>

            for each element utilises merge to compute the key (i.e. firstId) and value (i.e. List<String>)

            toMap

            listEntityComposite.stream()
                               .collect(toMap(e -> e.getId().getFirstId(), 
                                         v ->  new ArrayList<>(singletonList(v.getSecond())),
                                         (l, r) -> {l.addAll(r); return l;}));
            




            • 应用 keyMapper 功能 e - > e.getId()。getFirstId()提取地图键。

            • 应用 valueMapper 函数 v - > new ArrayList<>(singletonList(v.getSecond()))提取地图值。

            • 应用合并 function (l,r) - > {l.addAll(R);返回l;} 来解决关键冲突。

              • applies a keyMapper function e -> e.getId().getFirstId() to extract the map keys.
              • applies a valueMapper function v -> new ArrayList<>(singletonList(v.getSecond())) to extract the map values.
              • applies a merge function (l, r) -> {l.addAll(r); return l;} to resolve key collisions.
              • 总结一下, forEach + computeIfAbsent 方法和 groupingBy + 映射方法是你应该支持的两种方法,因为它们更具惯用性。

                To conclude, the forEach + computeIfAbsent approach and the groupingBy + mapping approach are the two you should favour in this specific case as they're the more idiomatic.

                这篇关于使用forEach,Java 8创建List列表(嵌套列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆