如何使用 java-streams 从列表创建地图?
How to create a map from list with java-streams?
我想用 java8 创建列表的地图。
class Person {
String name;
int age;
//etc
}
List<Person> persons;
Map<String, Person> personsByName = persons.stream().collect(
Collectors.toMap(Person::getName, Functions.identify());
结果:The type Person does not define getName(T) that is applicable here
为什么? Person::getName
有什么问题?
如果您在 Person
中有一个 getName()
方法,这应该没问题:
Map<String, Person> personsByName = persons.stream().collect(
Collectors.toMap(Person::getName, Function.identity()));
请注意,我还用 Function.identity()
更改了 Functions.identify()
(不存在)。我会认为这是你的错字。
我想用 java8 创建列表的地图。
class Person {
String name;
int age;
//etc
}
List<Person> persons;
Map<String, Person> personsByName = persons.stream().collect(
Collectors.toMap(Person::getName, Functions.identify());
结果:The type Person does not define getName(T) that is applicable here
为什么? Person::getName
有什么问题?
如果您在 Person
中有一个 getName()
方法,这应该没问题:
Map<String, Person> personsByName = persons.stream().collect(
Collectors.toMap(Person::getName, Function.identity()));
请注意,我还用 Function.identity()
更改了 Functions.identify()
(不存在)。我会认为这是你的错字。