Reputation: 69
My code:
final List<Employee> empList= getEmployeeList();
String empid = "1234";
Employee selectedEmp = new Employee();
for (Employee e1: empList) {
if (empid .equals(e1.getEmpid()))
selectedEmp = e1;
}
}
Now I want to rewrite the above code in Java 8.
I've tried the following, but without success. I can't figure out translate the if
-statement:
empList.stream()
.foreach( <how to apply if condition here>)
Upvotes: 0
Views: 305
Reputation: 28988
forEach()
isn't the appropriate tool here.
Firstly there's a method Iterable.forEach()
which you can invoke directly on a list without creating a stream, secondly Stream.forEach()
is not encouraged to be used in such a way by the Stream API documentation, it should be used with care in cases when you have no other tools suitable for the task.
Instead, you can use combination filter()
+ findFirst()
, which produces result of type Optional.
To provide a default value for the case when employee wasn't found (like in your code a dummy Employee
object created via no-args constructor) you can use Optional.orElseGet()
which expects a Supplier
that would be applied only when needed (when optional is empty).
public Employee findEmployee(String empid) {
return getEmployeeList().stream()
.filter(e -> empid.equals(e.getEmpid()))
.findFirst()
.orElseGet(Employee::new);
}
I strongly recommend you to get familiar with these tutorials on streams and lambda expressions
Upvotes: 8