Java流比较来自两个流的对象并创建新对象。

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

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&lt;Object1&gt; listOne = provider.getObjects().stream().collect(Collectors.toList());
List&lt;Object2&gt; listTwo = provider2.getObjects().stream().collect(Collectors.toList());

Now I want create List containg all possible Object1-Object2 combinations: List&lt;ObjectCombinations&gt; 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&lt;ObjectCombinations&gt; result =
    listOne.stream()
           .flatMap(o1 -&gt; listTwo.stream()
                                 .map(o2 -&gt; new ObjectCombinations(o1,o2)))
           .collect(Collectors.toList());

First you create a Stream&lt;Object1&gt;, 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&lt;ObjectCombinations&gt; res = 
       listOne.stream()
              .flatMap(a -&gt; listTwo.stream().map(b -&gt; new ObjectCombinations(a,b)))
              .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年10月14日 13:07:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64346939.html
匿名

发表评论

匿名网友

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

确定