将两个列表流式传输到地图中

时间:2016-12-05 18:31:46

标签: java java-8 java-stream

我正在尝试学习java 8流,但我将以下代码转换为流

parents = new ArrayList<Integer>() ...
children = new ArrayList<Intger>() ...
Map<Integer, List<Integer>> result = new HashMap<Integer, List<Integer>>();
for (Integer parentId : parents) {
    result.put(parentId, new ArrayList<Integer>(children));
}
return result;

像这样的东西不起作用

return parents.stream()
              .collect(toMap(p -> p, children));

Tunaki提供了导致答案的链接:How to create a map with Java stream API using a value outside the stream?

答案:

return parents.stream()
              .collect(toMap(Function.identity(), e -> new ArrayList<>(children)));

问题是我需要将一个元素传递给value函数,即使我不使用它而是从外部捕获。我试图给它一个不接受任何东西的功能。

1 个答案:

答案 0 :(得分:0)

Tunaki提供了导致答案的链接:How to create a map with Java stream API using a value outside the stream?

答案:

return parents.stream()
              .collect(toMap(Function.identity(), e -> new ArrayList<>(children)));

问题是我需要将一个元素传递给value函数,即使我不使用它而是从外部捕获。我试图给它一个不接受任何东西的功能。

相关问题