I am playing around with streams and lambdas in Java 8, as I have never used them before and was trying to convert the ages of everyone who is 20 to 19 and the printing out their names, but I get the following error
Cannot invoke map(Person::getName) on the primitive type void
.filter(person -> person.getAge() == 20)
.forEach(person -> person.setAge(19))
forEach is a terminal operation and will not return the stream it works on.
In general, you should avoid using
forEach to modify the stream, even as a final operation. Instead, you should use
map to modify the items of your stream.
Here is an example of how to do it, which includes a legitimate use of
people.stream() .filter(person -> person.getAge() == 20) .map(person -> new Person(person.getName(), person.getAge() -1 /*, ...*/)) .forEach(System.out::println);