我有一个类似这样的列表:
List<String> name = [[tom,john,peter,richered][manoj,satya,sachin,andrew]]
如何使用stream
将其转换为单个ArrayList答案 0 :(得分:2)
您可以在Java8中使用flatMap
,
List<List<String>> main = new ArrayList<>();
List<String> l1 = Arrays.asList("1", "2");
List<String> l2 = Arrays.asList("3", "4");
main.add(l1);
main.add(l2);
List<String> ans = main.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());
System.out.println(ans);
<子>的输出强> 子>
[1, 2, 3, 4]
答案 1 :(得分:1)
使用flatMap
:
List<List<String>> name = Lists.newArrayList(Lists.newArrayList("a", "b", "c", "d"), Lists.newArrayList("e", "f", "g"));
List<String> namesTogether = name.stream().flatMap(Collection::stream).collect(Collectors.toList());
System.out.println(namesTogether);
[a,b,c,d,e,f,g]