Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 streams: process every possible pair of elements from list

I have a Collection of elements of an arbitrary class. I want to iterate through the collection and perform some operation using the element and each other element of the collection one-by-one (excluding the element itself). Let it be List<Integer> for simplicity:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

With for loops it will be:

for (Integer i : list) {
    for (Integer j : list) {
        if (!i.equals(j)) System.out.println(i * 2 + j);  //just for example
    }
}

The question is how to do it with the Stream API?

That's what I have come to:

list.stream().forEach(i ->
    list.stream().forEach(j -> {
        if (!i.equals(j)) System.out.println(i * 2 + j);
    })
);

It doesn't look better than nested loop though. Is there a more elegant way?

like image 539
Oleg Mikhailov Avatar asked May 30 '16 12:05

Oleg Mikhailov


1 Answers

You can do this using the flatMap operation:

list.stream()
    .flatMap(i -> list.stream().filter(j -> !i.equals(j)).map(j -> i * 2 + j))
    .forEach(System.out::println);

This code is creating a Stream of the input list. It flat maps each element of the list with a stream created by the same list, where the current element was filtered out, and each element of this new list is the result of the i * 2 + j operation.

All the elements are then printed to the console.

like image 178
Tunaki Avatar answered Sep 21 '22 13:09

Tunaki