0

I have a list of unique longs. I would like to create a piece of code, which takes the list as an input and returns as a result a list of pairs which combines every element with each other excluding the same element, for example:

[1,2,3] -> [(1,2),(1,3),(2,1),(2,3),(3,1),(3,2)]

Is it possible to to this using Java Stream API? I tried something like this:

List<Pair<Long, Long>> result = myLongsList.stream().map(firstLong ->
        myLongsList.stream()
                .filter(secondLong -> !Objects.equals(firstLong, secondLong))
                .map(secondLong-> Pair.of(firstLong, secondLong))
                .collect(????))
            .collect(toList());

Is it possible to write the collector or change anything in the code above for it to return the results desired? I can of course to this with nested for loop, but I was wondering if I can do this with stream API.

Dawid
  • 153
  • 3
  • 18

1 Answers1

1

You don't need to collect the inner Streams, just use flatMap:

List<Pair<Long, Long>> result = 
    myLongsList.stream()
               .flatMap(firstLong -> myLongsList.stream()
                                                .filter(secondLong -> !Objects.equals(firstLong, secondLong))
                                                .map(secondLong-> Pair.of(firstLong, secondLong)))
               .collect(toList());

This flatMap will transform your Stream<Long> to a Stream<Pair<Long,Long>> of all pairs.

Eran
  • 387,369
  • 54
  • 702
  • 768