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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With