New*_*ser 4 java java-8 java-stream
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;
}
Run Code Online (Sandbox Code Playgroud)
How about:
SeniorEmployee sEmp = emp.stream()
.filter(SeniorEmployee.class::isInstance)
.findFirst()
.map(SeniorEmployee.class::cast)
.orElse(null);
Run Code Online (Sandbox Code Playgroud)
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
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |