Reputation: 35
Is it possible to get the same result (as I'm currently getting with the following nested for loops) using Stream
s?
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]
Upvotes: 3
Views: 256
Reputation: 393831
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 List
s 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]]
Upvotes: 6