简体   繁体   中英

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.

使用 skip 方法跳过列表中的 (n-1) 个元素, findFirst 方法会给你第 n 个元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM