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

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

empIdList.stream()
         .map(id-> getDepartment(id))
         .collect(Collectors.toMap(id, department:String -> department)

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

回答

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

empIdList.stream()    
         .collect(Collectors.toMap(Function.identity(), this::getDepartment);

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

  1. 如果可能,要么传递Setids 而不是 a List
  2. distinct()stream()和之间使用collect()
  3. 或提供一个虚拟合并函数作为第三个参数toMapCollectors.toMap(Function.identity(), this::getDepartment, (a,b) -> a)
  • To be on the safe side, make sure that the list does not contain duplicate ids by using `distinct()` or by providing a merging function when collecting to map.

以上是Java流api使用链内原始对象的引用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>