MOHAMMED SHAMAS
MOHAMMED SHAMAS

Reputation: 23

How to use Java 8 Stream API without collect method?

I have a problem to solve where I should find the nth Employee whose gender is Male from a list of Employees using java 8 streams, if nothing found return Optional empty.

class Employee{
   private int id;
   private String name;
   private String gender;
   
  //getters and setters
}

Below is the method which accepts a list of Employee objects and integer n where n denotes the nth male employee that has to be returned if exists.

Optional<Employee> nthMaleEmployee(List<Employee> employees, int n){

}

Below is my solution for the question using java 8 streams and collect method.

return employees.stream().filter((e)-> e.getGender().equalsIgnoreCase("male")).collect(Collectors.toList()).get(n-1);

Is there any solution with streams not using collect method? My problem statement is to use streams without using collect method.

Upvotes: 1

Views: 388

Answers (1)

Patrick
Patrick

Reputation: 1775

Use the skip method to skip (n-1) elements in the list and findFirst method would give you the nth element.

Upvotes: 2

Related Questions