Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the second element in a stream satisfying some condition? [duplicate]

I want to display the second element of the stream for which the name starts 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 findAny(), it returns the first element in the stream (same as findFirst()) and I want the second one.

like image 695
Hamza Torjmen Avatar asked Dec 27 '16 13:12

Hamza Torjmen


1 Answers

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));
like image 195
Eran Avatar answered Nov 07 '22 04:11

Eran