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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With