我试图使用Streams创建一个String
的二维数组:
String[] fruit1DArray;
String[][] fruit2DArray;
Map<String, String> fruitMap = new HashMap<>();
fruitMap.put("apple", "red");
fruitMap.put("pear", "green");
fruitMap.put("orange", "orange");
fruit1DArray = fruitMap.entrySet()
.stream()
.map(key -> key.getKey())
.toArray(size -> new String[size]);
fruit2DArray = fruitMap.entrySet()
.stream()
.map(entry-> new String[]{entry.getKey()})
.toArray(size -> new String[size][1]);
System.out.println(Arrays.deepToString(fruit1DArray));
System.out.println(Arrays.deepToString(fruit2DArray));
输出结果为:
[orange, apple, pear]
[[orange], [apple], [pear]]
我需要的输出是:
[orange, apple, pear]
[[orange, orange], [apple, red], [pear, green]]
.toArray(Float[][]::new);
而不是.toArray(size -> new Float[size][1]);
,后者浪费性能,因为它会用被后来覆盖的子数组填充新数组。 - Holger