我正在尝试使用流创建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]]
答案 0 :(得分:6)
您忘记了从输入Map
中获取值:
fruit2DArray = fruitMap.entrySet()
.stream()
.map(e -> new String[]{e.getKey(),e.getValue()})
.toArray(String[][]::new);
输出:
[[orange, orange], [apple, red], [pear, green]]