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

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

问题描述

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

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.

推荐答案

没有简单的内置方法可以做您想做的事,因为您的 list.toArray() 只能返回存储在list 在您的情况下也将是列表.

There is no simple builtin way to do what you want because your list.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()]);
}

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

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

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

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