将字符串集合转换为以输入作为键映射器的映射。

huangapple go评论58阅读模式
英文:

Converting String Collection to a Map with input as the key mapper

问题

这里有一个示例:

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

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

}

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

英文:

Here's an example:

Map&lt;String, Student&gt; getStudentsById(Collection&lt;String&gt; ids) {

  return ids.stream()
       .collect(Collectors.toMap(&lt;id-here&gt;, id -&gt; new Student(id))

}

I'm not sure how to use Collectors.toMap, so that key is the stream element (here in case the ID), and value is some object constructed from the key.

答案1

得分: 1

你正在向 Collectors.toMap() 传递一个 String 和一个 Student,但你应该传递一个 Function<? super String, ? extends String> 和一个 Function<? super String, ? extends Student>。应该修改为:

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

You are passing a String and a Student to Collectors.toMap(), when you should be passing a Function&lt;? super String,? extends String&gt; and a Function&lt;? super String,? extends Student&gt;.

It should be:

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

huangapple
  • 本文由 发表于 2020年8月25日 14:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63573240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定