PAA :
How to set the values in Java 8 in filter ? I want to set emailId to null where firstName is Raj. How can I do that in Java8?
public class EmployeeDemo {
public static void main(String[] args) {
Employee e1 = new Employee("John", "Kerr", "[email protected]");
Employee e2 = new Employee("Parag", "Rane", "[email protected]");
Employee e3 = new Employee("Raj", "Kumar", "[email protected]");
Employee e4 = new Employee("Nancy", "Parate", "[email protected]");
List<Employee> employees = new ArrayList<>();
employees.add(e1);
employees.add(e2);
employees.add(e3);
employees.add(e4);
employees.stream().filter(e -> {
if(e.getFirstName().equals("Raj")) {
e.setEmail(null);
}
}).
}
}
ByeBye :
Filter method should return boolean
and I think shouldn't have any side effects. In your case simple loop will do the job:
for(Employee employee: employees) {
if(e.getFirstName().equals("Raj")) {
e.setEmail(null);
}
}
But if you really want to use stream:
employees.stream() //get stream
.filter(e -> e.getFirstName().equals("Raj")) //filter entries with first name Raj
.forEach(e -> e.setEmail(null)); //for each of them set email to null
or (if you want to do process the whole list and return changed with all entries:
employees.stream() //get stream
.map(e -> {
if(e.getFirstName().equals("Raj")) {
e.setEmail(null);
}
return e;
})
.collect(Collectors.toList());