gpt4 book ai didi

java - 列表<列表<字符串>>到字符串[][]

转载 作者:行者123 更新时间:2023-12-01 18:07:38 29 4
gpt4 key购买 nike

java中有没有快捷方式可以转换

List<List<String>> 

String[][]

? toArray 不起作用:

List<List<String>> list = new ArrayList<>();
list.add(Collections.singletonList("test"));
String[][] array = list.toArray(new String[0][]);
System.out.println(array);

Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
at main(Api.java:1001)

这不是 Convert nested list to 2d array 的重复项因为我正在寻找快捷方式/库,而不是基本实现

最佳答案

这里有一些 Java 8 lambda 可以做到这一点:

// original List<List<String>>
List<List<String>> nestedList = new ArrayList<>();
// adding test values
nestedList.add(new ArrayList<String>(){{add("a");add("b");}});
nestedList.add(new ArrayList<String>(){{add("c");add("c");}});
nestedList.add(new ArrayList<String>(){{add("e");add("f");}});
// printing the original List<List<String>>
System.out.println(nestedList);
String[][] nestedArray = nestedList
// using the stream API
.stream()
// mapping each `List`...
.map(
// ... to a resulting array
(l) -> l.toArray(new String[l.size()])
)
// collecting as a List<String[]>
.collect(Collectors.toList())
// converting the resulting List<String[]> to a String[][]
.toArray(new String[nestedList.size()][]);
// printing the resulting 2-dimensional array
System.out.println(Arrays.deepToString(nestedArray));

输出

[[a, b], [c, c], [e, f]]
[[a, b], [c, c], [e, f]]

关于java - 列表<列表<字符串>>到字符串[][],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35085850/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com