【问题标题】:Java stream api using reference of original object within chain使用链内原始对象引用的 Java 流 api
【发布时间】:2021-05-18 10:01:42
【问题描述】:

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

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

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

【问题讨论】:

    标签: java lambda java-8 java-stream


    【解决方案1】:

    你可以避开map函数,直接调用collect

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

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

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

    【讨论】:

    • 为了安全起见,通过使用distinct()或在收集到地图时提供合并功能,确保列表不包含重复的id。
    • Manish,正如@Eritrean 指出的那样,注意接收非唯一id 列表的可能性。我已经用相关信息更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 2016-03-24
    相关资源
    最近更新 更多