Java流api使用链内原始对象的引用

Man*_*sal 1 java lambda java-8 java-stream

我正在尝试从列表创建一个 Map,而 Map 的值将是某种转换的结果,这就是我的代码的样子。

empIdList.stream()
         .map(id-> getDepartment(id))
         .collect(Collectors.toMap(id, department:String -> department)
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我希望将其id用作键和department值。你能帮我实现我的预期结果吗?

Gau*_*m M 6

您可以避免该map功能并直接调用collect

empIdList.stream()    
         .collect(Collectors.toMap(Function.identity(), this::getDepartment);
Run Code Online (Sandbox Code Playgroud)

如果列表没有唯一的 id,那么它会导致IllegalStateException这样:

  1. 如果可能,要么传递Setids 而不是 a List
  2. distinct()stream()和之间使用collect()
  3. 或提供一个虚拟合并函数作为第三个参数toMapCollectors.toMap(Function.identity(), this::getDepartment, (a,b) -> a)

  • 为了安全起见,请通过使用“distinct()”或在收集到地图时提供合并函数来确保列表不包含重复的 id。 (2认同)