将嵌套列表转换为2d数组 [英] Convert nested list to 2d array

查看:168
本文介绍了将嵌套列表转换为2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将嵌套列表转换为二维数组。

I'm trying to convert a nested list into a 2d array.

List<List<String>> list = new ArrayList<>();

list.add(Arrays.asList("a", "b", "c"));
list.add(Arrays.asList("dd"));
list.add(Arrays.asList("eee", "fff"));

我想把它变成 String [] [] 。我尝试了以下内容:

I want to make this a String[][]. I've tried the following:

String[][] array = (String[][]) list.toArray();      // ClassCastException

String[][] array = list.toArray(new String[3][3]);   // ArrayStoreException

String[][] array = (String[][]) list.stream()        // ClassCastException
    .map(sublist -> (String[]) sublist.toArray()).toArray();

有没有办法有效?请注意,我不会知道列表的大小,直到运行时,它可能是锯齿状的。

Is there a way that works? Note that I won't know the size of the list until runtime, and it may be jagged.

推荐答案

没有简单内置的方式来做你想要的,因为你的 toArray 只能返回列表中存储的元素数组,在你的情况下也是列表。

There is no simple builtin way to do what you want because your toArray can return only array of elements stored in list which in your case would also be lists.

最简单的解决方案是创建二维数组,并从每个嵌套列表中填入 toArray 的结果。

Simplest solution would be creating two dimensional array and filling it with results of toArray from each of nested lists.

String[][] array = new String[list.size()][];

int i = 0;
for (List<String> nestedList : list) {
    array[i++] = nestedList.toArray(new String[nestedList.size()]);
}

(如果您使用带有流的Java 8,则可以缩短此代码 Alex做了

(you can shorten this code if you are using Java 8 with streams just like Alex did)

这篇关于将嵌套列表转换为2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆