user6248190 user6248190 - 1 month ago 11
Java Question

Java 8 stream getting cannot invoke map on primitive type void

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


Here is my code

System.out.println(
people.stream()
.filter(person -> person.getAge() == 20)
.forEach(person -> person.setAge(19))
.map(Person::getName));


If someone could tell me why this is happening or let me know how to improve or amend this code, it would be greatly appreciated.

Answer

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 forEach :

people.stream()
      .filter(person -> person.getAge() == 20)
      .map(person -> new Person(person.getName(), person.getAge() -1 /*, ...*/))
      .forEach(System.out::println);