Converting nested lists using java streams
•
Java
Is it possible to use streams to get the same results (as I currently get using the following nested for loop)?
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 want this response:
[[JOHN,ADAM],[ALEX,REX]]
Use the following streams:
list. stream(). flatMap(l – > l.stream()). map(String :: toUpperCase). collect(Collectors.toList());
I can only get such things:
[JOHN,ADAM,ALEX,REX]
Solution
Flatmap doesn't help you because you don't want flat output You should convert each internal list to an uppercase 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,REX]]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码