Transforming a nested List using java Streams

Dawid :

Is it possible to get the same result (as I'm currently getting with the following nested for loops) using Streams?

List<String> people = Arrays.asList("John", "Adam");
List<String> dogs = Arrays.asList("alex", "rex");

List<List<String>> list = new ArrayList<List<String>>();
list.add(people);
list.add(dogs);

List<List<String>> list2 = new ArrayList<List<String>>();
for (int i = 0; i < list.size(); i++) {
    list2.add(new ArrayList<>());
    for (int j = 0; j < list.get(i).size(); j++) {
        list2.get(i).add(list.get(i).get(j).toUpperCase());
    }
}
System.out.println(list2);

I would like to get something like this in response:

[[JOHN, ADAM], [ALEX, REX]]

Using the following Stream:

list.stream().flatMap(l -> l.stream()).map(String::toUpperCase).collect(Collectors.toList());

I'm only able to get something like this:

[JOHN, ADAM, ALEX, REX]
Eran :

flatMap won't help you, since you don't want a flat output. You should transform each inner List separately into an upper case List, and then collect all these Lists into the final nested output List.

List<List<String>> list2 = list.stream()
        .map(l -> l.stream().map(String::toUpperCase).collect(Collectors.toList()))
        .collect(Collectors.toList());

Output:

[[JOHN, ADAM], [ALEX, REX]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88154&siteId=1