英文:
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<String, Student> getStudentsById(Collection<String> ids) {
return ids.stream()
.collect(Collectors.toMap(<id-here>, id -> 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<? super String,? extends String>
and a Function<? super String,? extends Student>
.
It should be:
Map<String, Student> idToStudent = ids.stream()
.collect(Collectors.toMap(Function.identity(), id -> new Student(id)));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论