[[a, a, a], [b, b, b], [c, c]]
[a, a, a, b, b, b, c, c, c]
I'd like to do this, but is there any way I can do it on stream at once?
// This is what it looks like when you loop normally.
List innerA=Arrays.asList("a", "a", "a");
List innerB=Arrays.asList("b", "b", "b");
List innerC=Arrays.asList("c", "c", "c");
List<List>outer=Arrays.asList(innerA, innerB, innerC);
System.out.println(outer);
// [[a,a,a], [b,b,b], [c,c,c]]
List innerABC = new ArrayList<>();
for (List inner:outer) {
innerABC.addAll(inner);
}
System.out.println (innerABC);
// [a, a, a, b, b, b, c, c, c]
You may be able to use Stream#flatMap(...).
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class StreamTest{
public static void main(String...args) {
List<String> innerA=Arrays.asList("a", "a", "a");
List<String> innerB=Arrays.asList("b", "b", "b");
List<String> innerC=Arrays.asList("c", "c", "c");
List<List<String>>outer=Arrays.asList(innerA,innerB,innerC);
// List innerABC = new ArrayList<>();
// for (List inner:outer) {
// innerABC.addAll(inner);
//}
List<String>innerABC=outer.stream()
.flatMap(lst->lst.stream())
.collect(Collectors.toList());
System.out.println (innerABC);
}
}
It's a little strange, but how about this one?
Optional<List<String>>innerABC=outer.stream()
.reduce(s1, s2)->concat(s1.stream(), s2.stream())
.collect(Collectors.toList()));
if(innerABC.isPresent()){
System.out.println(innerABC.get());
}
© 2024 OneMinuteCode. All rights reserved.