Java – use streams to map to 2D arrays
•
Java
I'm trying to create a 2D string array 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]]
My subsequent output is:
[orange,pear] [[orange,orange],[apple,red],[pear,green]]
I mean https://stackoverflow.com/a/47397601/887235
Solution
You forgot to get the value from the input map:
fruit2DArray = fruitMap.entrySet()
.stream()
.map(e -> new String[]{e.getKey(),e.getValue()})
.toArray(String[][]::new);
Output:
[[orange,green]]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
