How to find the second element in the stream that satisfies some condition?

I want to display the second element of the stream for which the name begins with 's'.

I tried:

employees.stream()
         .filter(e -> e.getName().charAt(0) == 's')
         .findAny()
         .ifPresent(e -> System.out.println("Employee : " + e));

However, when I use it findAny(), it returns the first element in the stream (same as findFirst()), and I want the second.

+4
source share
1 answer

You can skip the first match by adding skip(1)after the filter:

employees.stream()
         .filter(e -> e.getName().charAt(0) == 's')
         .skip(1)
         .findAny()
         .ifPresent(e -> System.out.println("Employee : " + e));
+9
source

Source: https://habr.com/ru/post/1665005/


All Articles