Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

java - Convert nested list to 2d array

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"));

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do this:

String[][] array = list.stream()
    .map(l -> l.stream().toArray(String[]::new))
    .toArray(String[][]::new);

It creates a Stream<List<String>> from your list of lists, then from that uses map to replace each of the lists with an array of strings which results in a Stream<String[]>, then finally calls toArray(with a generator function, instead of the no-parameter version) on that to produce the String[][].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...