2

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?

Philipp
  • 335
  • 1
  • 6
  • 17

2 Answers2

2

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

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());
Eklavya
  • 17,618
  • 4
  • 28
  • 57