vicolored
vicolored

Reputation: 835

Print list items with Java streams

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

Upvotes: 43

Views: 107271

Answers (6)

Matt
Matt

Reputation: 149

If you don't want to modify the original values, but rather just capitalize the printed output, you can do this:

list.forEach(s -> System.out.println(s.toUpperCase()));

Upvotes: 1

Alferd Nobel
Alferd Nobel

Reputation: 3979

Ensure you had generated the toString() method for the class type your printing like :

 @Override
    public String toString() {
        return "YourClassName{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", info='" + info + '\'' +
                '}';
    }

then System.out.println(listObj); should print the result list of objects as :

[YourClassName{name='Muller', age=40, info='Sr.Developer'}, YourClassName{name='Zoe', age=34, info='Sr.Developer'}, YourClassName{name='Ghai', age=89, info='Principal Developer'}]

Upvotes: 1

Q10Viking
Q10Viking

Reputation: 1121

You can look at the following example that can be executed in java8 environment.

import java.util.Arrays;
import java.util.List;
public class Main{
    public static void main(String[] args){
        // create a list
        List<String> mylist = Arrays.asList("Hello","World");
        mylist.stream()
              .map(String::toUpperCase)
              .forEach(System.out::println);
    }
}

/*output
HELLO
WORLD
*/

Upvotes: 0

Holger
Holger

Reputation: 298579

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);

Upvotes: 70

Summved Jain
Summved Jain

Reputation: 890

The best way to print all of them in one go is

Arrays.toString(list.toArray())

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 69035

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());

Upvotes: 5

Related Questions