[英]Programmatically create 2D ArrayList and then create a single ArrayList from it
Programmatically create 2D ArrayList in java and then create a single ArrayList from it.以编程方式在 java 中创建 2D ArrayList,然后从中创建单个 ArrayList。
I have an ArrayList<Integer> IntegerArraylist
of 5 Integers like this {1,2,3,4,5};
我有一个像这样的 5 个整数的
ArrayList<Integer> IntegerArraylist
{1,2,3,4,5};
Based on this I have to create 2D ArrayList like:基于此,我必须创建 2D ArrayList,例如:
ArrayList<ArrayList<String>> StringArraylist;
Like this:像这样:
{{a}, {b, c, d, e, f}, {g, h}, {i, j, k}, {l}}
Now based on this I have to convert it to single ArrayList like this:现在基于此,我必须将其转换为单个 ArrayList,如下所示:
{a, b, c, d, e, f, g, h, i, j, k, l}
How can we do this?我们应该怎么做?
List<String> list = new ArrayList<String>();
for (String[] array : YOUR_2D_ARRAY) {
list.addAll(Arrays.asList(array));
I think the easiest way to do this is using StreamAPI我认为最简单的方法是使用 StreamAPI
public static void main(String[] args) {
String[][] arr = {
{"a"},
{"b", "c", "d", "e", "f"},
{"g", "h"}
// and so on
};
List<List<String>> stringArraylist = Arrays.stream(arr)
.map(Arrays::asList)
.collect(Collectors.toList());
List<String> merged = stringArraylist.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(merged);
}
Or, simple use for-each loop:或者,简单地使用 for-each 循环:
List<String> merged = new ArrayList<>();
for(List<String> list : stringArraylist) {
merged.addAll(list);
}
Note that you need to use the List
interface and not the ArrayList
implementation.请注意,您需要使用
List
接口而不是ArrayList
实现。
You can use streams
with flatMap
您可以将
streams
与flatMap
一起使用
Stream<String> oneDStream = StringArraylist.stream().flatMap((Function<ArrayList<String>, Stream<String>>) strings -> strings.stream());
List<String> oneDList = oneDStream.collect(Collectors.toList());
oneDList.forEach(s -> {
System.out.print(" "+ s);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.