JAVA 8:如何使用2个流合并两个列表

huangapple go评论63阅读模式
英文:

JAVA 8 : HOW TO MERGE TWO LIST USING 2 STREAM

问题

你好我写了以下的代码

    for (Object1 o1 : listObject1) {
      boolean found = false;
      for (Object2 o2 : listObject2) {
        found = o2.getKey().equals(o1.getKey());
        if (found) break;
      }
      if (!found) listObject2.add(new Object2(o1.getKey()));
    }

但是我想要在Java 8中使用流streams来编写我尝试使用flatMap但是没有成功有人可以帮助我吗并且解释一下flatMap的用途吗

谢谢
英文:

Hello I wrote the following code

for (Object1 o1 : listObject1) {
  boolean found = false;
  for (Object2 o2 : listObject2) {
    found = o2.getKey().equals(o1.getKey());
    if (found) break;
  }
  if (!found) listObject2.add(new Object2(o1.getKey()));
}

But I want to write it in Java 8 using streams. I tried to use flatMap but I did not succeed. Can someone help me ? and explain to me the use of flatmap ?

Thanks

答案1

得分: 5

如果您的目标是提高可读性,那么在我看来,您能够获得的最大收益不是通过流操作,而是通过缓存第二个列表中元素的键(如果您愿意,也可以使用流操作来实现):

Set<String> keysInList2 = listObject2.stream()
                                     .map(Object2::getKey)
                                     .collect(Collectors.toSet());

如果您可以向该集合中添加来自listObject1的另一个对象的键,那么这意味着这样的键尚未存在于集合中。在这种情况下,您还应将具有此键的新Object2元素添加到listObject2中:

for (Object1 o1 : listObject1) {
    if (keysInList2.add(o1.getKey())){
        listObject2.add(new Object2(o1.getKey()));
    }
}
英文:

If your goal is to improve readability then IMO biggest gain you will get is not via streams but via caching keys of elements from second list (it can be done via streams if you want)

Set&lt;String&gt; keysInList2 = listObject2.stream()
                                     .map(Object2::getKey)
                                     .collect(Collectors.toSet());

If you can add to that set another key of object from listObject1, then it means such key was not yet present in set. In such case you should also add new Object2 element with such key to listObject2

for (Object1 o1 : listObject1) {
    if (keysInList2.add(o1.getKey())){
        listObject2.add(new Object2(o1.getKey()));
    }
}

huangapple
  • 本文由 发表于 2020年4月9日 06:26:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/61111040.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定