3

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 Answer 1

6

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Time to fix the already linked answer to similarly use .toArray(Float[][]::new); instead of .toArray(size -> new Float[size][1]); which wastes performance populating the new array with subarrays which are overwritten afterwards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.