【问题标题】:Converting String Collection to a Map with input as the key mapper [duplicate]将字符串集合转换为带有输入作为键映射器的映射 [重复]
【发布时间】:2020-12-13 19:32:12
【问题描述】:

这是一个例子:

Map<String, Student> getStudentsById(Collection<String> ids) {

  return ids.stream()
       .collect(Collectors.toMap(<id-here>, id -> new Student(id))

}

我不确定如何使用Collectors.toMap,所以key 是流元素(这里是ID),而value 是从key 构造的某个对象。

【问题讨论】:

标签: java java-8 java-stream collectors


【解决方案1】:

您将 StringStudent 传递给 Collectors.toMap(),而您应该传递 Function&lt;? super String,? extends String&gt;Function&lt;? super String,? extends Student&gt;

应该是:

Map<String, Student> idToStudent = ids.stream()
     .collect(Collectors.toMap(Function.identity(), id -> new Student(id)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多