我有一个学生列表,我想将其转换为 Map<String, Integer>
,其中映射键应该是学生的名字。为了使代码示例简单,我将 map 值指定为 1
:
final Map<String, Integer> map = someStudents.stream().collect(
Collectors.toMap(Student::getFirstName, 1));
编译器提示:
non-static method getFirstName() cannot be referenced from a static context
有什么想法吗?我很困惑,因为许多示例使用相同的方法将引用传递给非静态方法。为什么编译器在这里看到静态上下文?
最佳答案
The value mapper should be a function ,即:
.collect(Collectors.toMap(Student::getFirstName, s -> 1));
函数 s -> 1
本质上将学生作为输入,并在这种特定情况下返回 1
作为映射值。
以下代码无效,因为文字值 1
不是函数。
.collect(Collectors.toMap(Student::getFirstName, 1));
关于java - 不能从 Collectors.toMap 中的静态上下文引用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51614284/