Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map to 2d array with Streams

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

like image 650
Vicky Avatar asked May 23 '26 22:05

Vicky


1 Answers

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]]
like image 200
Eran Avatar answered May 25 '26 10:05

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!