Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print list items with Java streams

Tags:

java

java-8

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

like image 737
vicolored Avatar asked Jul 15 '15 14:07

vicolored


People also ask

How do I get a List of fields from a List of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

Can we print List directly in Java?

Print List in Java Using forEach() The last way to print a list in Java is to use the forEach() method introduced in Java 8. Every ArrayList has a forEach() method that processes every individual item from the List . We will use it to print out every item.

How can we get a stream from a List in Java?

Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source.


2 Answers

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); 
like image 179
Holger Avatar answered Sep 25 '22 00:09

Holger


If you want to print and save modified values simultaneously you can do

List<String> newValues = myList.stream().map(String::toUpperCase) .peek(System.out::println).collect(Collectors.toList()); 
like image 42
Aniket Thakur Avatar answered Sep 27 '22 00:09

Aniket Thakur