我想用 java8 创建一个列表的映射。
class Person {
String name;
int age;
//etc
}
List<Person> persons;
Map<String, Person> personsByName = persons.stream().collect(
Collectors.toMap(Person::getName, Functions.identify());
结果:类型 Person 没有定义适用于此处的 getName(T)
为什么? Person::getName
有什么问题?
最佳答案
如果你在 Person
中有一个 getName()
方法,这应该没问题:
Map<String, Person> personsByName = persons.stream().collect(
Collectors.toMap(Person::getName, Function.identity()));
请注意,我还将 Functions.identify()
(不存在)更改为 Function.identity()
。我会假设这是你的错字。
关于java - 如何使用 java-streams 从列表创建 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30350610/