You can write multiple statements inside of forEach :
public class Person
{
public Person(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name + "(" + age + ")";
}
}
public class LambdaPeople
{
public static void main(String[] args) {
Person andy = new Person("Andy", 19);
Person bob = new Person("Bob", 21);
Person caroline = new Person("Caroline", 20);
List<Person> people = new ArrayList<>();
people.add(caroline);
people.add(andy);
people.add(bob);
people.stream()
.filter(person -> person.getAge() == 20)
.forEach(person -> {
person.setAge(19);
System.out.println(person);
});
}
}
It returns :
Caroline(19)
The two next methods are for documentation purpose. peek and map are intermediate operations. Without forEach at the end, they wouldn't be executed at all.
If you want to use map :
people.stream()
.filter(person -> person.getAge() == 20)
.map(person -> {
person.setAge(19);
return person;
})
.forEach(System.out::println);
If you want to use peek :
people.stream()
.filter(person -> person.getAge() == 20)
.peek(person -> person.setAge(19))
.forEach(System.out::println);