英文:
Java streams compare object from two streams and create new Object
问题
我有两个列表:
List<Object1> listOne = provider.getObjects().stream().collect(Collectors.toList());
List<Object2> listTwo = provider2.getObjects().stream().collect(Collectors.toList());
现在我想创建一个包含所有可能的 Object1
-Object2
组合的列表:List<ObjectCombinations> result;
class ObjectCombinations {
Object1 object1;
Object2 object2;
public ObjectCombinations(Object1 object1, Object2 object2) {
this.object1 = object1;
this.object2 = object2;
}
}
如何在 Java 8 的流中实现这个功能?
英文:
I have two Lists:
List<Object1> listOne = provider.getObjects().stream().collect(Collectors.toList());
List<Object2> listTwo = provider2.getObjects().stream().collect(Collectors.toList());
Now I want create List containg all possible Object1
-Object2
combinations: List<ObjectCombinations> result;
class ObjectCombinations {
Object1 object1;
Object2 object2;
public ObjectCombinations(Object1 object1, Object2 object2) {
this.object1 = object1;
this.object2 = object2;
}
}
How is that possible with java 8 streams?
答案1
得分: 2
你可以使用 flatMap
来获取所有的组合:
List<ObjectCombinations> result =
listOne.stream()
.flatMap(o1 -> listTwo.stream()
.map(o2 -> new ObjectCombinations(o1,o2)))
.collect(Collectors.toList());
首先,你创建一个 Stream<Object1>
,然后使用 flatMap
将该流的每个元素与 listTwo
的所有元素组合,并创建 ObjectCombinations
实例,然后将其收集到一个 List
中。
英文:
You can use flatMap
to get all the combinations:
List<ObjectCombinations> result =
listOne.stream()
.flatMap(o1 -> listTwo.stream()
.map(o2 -> new ObjectCombinations(o1,o2)))
.collect(Collectors.toList());
First you create a Stream<Object1>
, then you use flatMap
to combine each element of that stream with all the elements of listTwo
, and create the ObjectCombinations
instances, which you collect to a List
.
答案2
得分: 1
你可以在需要遍历第二个列表并创建ObjectCombinations并扁平化列表的地方使用flatMap
。
List<ObjectCombinations> res =
listOne.stream()
.flatMap(a -> listTwo.stream().map(b -> new ObjectCombinations(a, b)))
.collect(Collectors.toList());
英文:
You can use flatMap
where you can stream over 2nd list and create ObjectCombinations and flatten the list.
List<ObjectCombinations> res =
listOne.stream()
.flatMap(a -> listTwo.stream().map(b -> new ObjectCombinations(a,b)))
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论