英文:
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<String> 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()));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论