vicolored vicolored - 2 months ago 17
Java Question

Print list items with java 8 api

I can use something like :

.forEach(System.out::print)


to print my list items but if I have another operation to do before printing I can't use it like :

mylist.replaceAll(s -> s.toUpperCase()).forEach(System.out::print)


I'm getting an error : void cannot be dereferenced

Answer

You have to decide. When you want to modify the list, you can’t combine the operations. You need two statements then.

myList.replaceAll(String::toUppercase);// modifies the list
myList.forEach(System.out::println);

If you just want to map values before printing without modifying the list, you’ll have to use a Stream:

myList.stream().map(String::toUppercase).forEachOrdered(System.out::println);
Comments