使用流映射到二维数组

时间:2018-07-09 06:56:49

标签: java arrays dictionary java-stream

我正在尝试使用流创建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]]

我指的是https://stackoverflow.com/a/47397601/887235

1 个答案:

答案 0 :(得分:6)

您忘记了从输入Map中获取值:

fruit2DArray = fruitMap.entrySet()
                       .stream()
                       .map(e -> new String[]{e.getKey(),e.getValue()})
                       .toArray(String[][]::new);

输出:

[[orange, orange], [apple, red], [pear, green]]