使用流映射到二维数组

我正在尝试String使用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));

输出为:


[orange, apple, pear]

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

我追求的输出是:


[orange, apple, pear]

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

我指的是https://stackoverflow.com/a/47397601/887235


森栏
浏览 154回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java