user6248190 user6248190 - 1 year ago 136
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

.filter(person -> person.getAge() == 20)
.forEach(person -> person.setAge(19))

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 Source

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 :
      .filter(person -> person.getAge() == 20)
      .map(person -> new Person(person.getName(), person.getAge() -1 /*, ...*/))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download