Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first instances of a subclass from a list using java 8

I have two subclasses of a class. Now I have a list that can contain either of the subclasses.

Now I need to iterate through the list and get the first occurrence of Subclass B.

I have used the below and looking for Java 8/stream/lambda way of doing this.

SeniorEmployee sEmp = null;    
for(Employee emp: empList){
if(emp instanceof SeniorEmployee)
 sEmp = emp;
 break;
}
like image 665
NewUser Avatar asked Jan 27 '23 13:01

NewUser


1 Answers

How about:

SeniorEmployee sEmp = emp.stream()
                         .filter(SeniorEmployee.class::isInstance)
                         .findFirst()
                         .map(SeniorEmployee.class::cast)
                         .orElse(null);

Where you can put in some other default value in the orElse section. This solution uses findFirst to get the first element that matches the Predicate

Also note that orElse(null) is to make the code equivalent to the code in the question. It is best to give a value other than null, as that defeats the entire purpose of the Optional

like image 78
GBlodgett Avatar answered Feb 02 '23 12:02

GBlodgett