Map to 2d array with Streams

十年热恋 提交于 2021-02-19 04:17:26

问题


I am trying to create a 2d array of String using Streams:

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

The output is:

[orange, apple, pear]
[[orange], [apple], [pear]]

The output I am after is:

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

I am referring https://stackoverflow.com/a/47397601/887235


回答1:


You forgot to grab the value from your input Map:

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

Output:

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


来源:https://stackoverflow.com/questions/51239708/map-to-2d-array-with-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!