问题
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