将列表的列表转换为java中的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29635193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert List of List into list in java
提问by Manu Joy
List<List<String>> superlist = new ArrayList<List<String>>();
List<String> list1 = new ArrayList<String>();
list1.add("a1");
list1.add("a2");
List<String> list2 = new ArrayList<String>();
list2.add("b1");
list2.add("b2");
List<String> list3= new ArrayList<String>();
list3.add("c1");
list3.add("c2");
superlist.add(list1);
superlist.add(list2);
superlist.add(list3);
List<String> result= new ArrayList<>();
Now I want to create a new list which contains all the values in superList
.
Here result should contain a1,a2,b1,b2,c1,c2
现在我想创建一个新列表,其中包含superList
. 这里的结果应该包含a1,a2,b1,b2,c1,c2
采纳答案by Rahul Tripathi
Try like this using flatMap
:
尝试这样使用flatMap
:
List<List<Object>> list =
List<Object> lst = list.stream()
.flatMap(x -> x.stream())
.collect(Collectors.toList());
回答by camelsaucerer
You would have to loop through every List
in your superlist
object in order to get all of the contents. You can use the addAll()
method to copy each list's contents to your new List
:
你将不得不遍历每个List
在你的superlist
对象,以获得所有的内容。您可以使用该addAll()
方法将每个列表的内容复制到新的List
:
List<String> result = new ArrayList<String>();
for (List<String> list : superlist) {
result.addAll(list);
}
回答by Manu Joy
superlist.forEach(e -> result.addAll(e));
Now after some reasarch, I found this way.
现在经过一些研究,我找到了这种方式。
回答by Mick Mnemonic
If you're on Java < 8 (and cannot use Stream
s), you can do this in a one-liner with Guava's Iterables.concat
:
如果您使用的是 Java < 8(并且不能使用Stream
s),您可以使用 Guava's 单线执行此操作Iterables.concat
:
List<String> merged = Lists.newArrayList(Iterables.concat(superList));