Java8 Stream API findFirst method to get the first element.
Retrieves the first element that can be retrieved with the findFirst method. If there is more than one element matching the condition, it returns the element from the Stream that is the earliest in order.
Suppose there is an Employee class.
public class Employee { private String name; private int age; public Employee(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Create a list of Employees and retrieve the first element with the findFirst method. findFirst method return value is Optional<T>.
List<Employee> list = new ArrayList<Employee>(); list.add(new Employee("tanaka", 44)); list.add(new Employee("takahashi", 40)); list.add(new Employee("minami", 30)); list.add(new Employee("higashiguchi", 32)); list.add(new Employee("adachi", 200)); list.add(new Employee("rasubosu", 25)); Optional<Employee> emp = list.stream().findFirst(); emp.ifPresent(e -> System.out.println(e.getName() + " : " + e.getAge()));
The ifPresent method takes a Consumer as an argument and will call the Consumer with that element only if the element exists.
If the element does not exist in emp, Consumer will not work. accept method of Consumer has one argument and no return value.
Functional Interface Consumer
@FunctionalInterface public interface Consumer<T> { void accept(T t); }
In addition to the findFirst method, there is a findAny method.
The following is the ifPresent method of the Optional class. if value is not null, then the Consumer#accept method is executed. if value is null, then the accept method is not called.
public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }
コメント