静态上下文无法访问收集器中的非静态 [英] Static context cannot access non-static in Collectors
问题描述
我有一群学生。首先,我想用标记对它们进行分组。然后我想进一步将这些集合分组到同名学生中。
I have group of students. First I want to group them by the marks. Then I want to further group those sets into same name students together.
Map<Integer,Map<String,List<String>>> groupping = students.stream()
.collect(Collectors.groupingBy(Student::getMarks,
Collectors.mapping(Student::getName,Collectors.toList())));
我收到错误消息,
无法从静态上下文中引用非静态方法。
Non-static method cannot be refered from a static context.
是。我非常清楚,如果没有实例,我就无法引用非静态方法。但是对于所有这些流操作,我真的很困惑。
Yes. I am pretty much aware that I cannot refer a non-static method without having an instance. But with all these stream operations, I'm bit confused what has gone wrong really.
而不是如何解决这个问题;我真的想知道这里发生了什么。感谢您的任何投入!
Rather than how to fix this; I really want to know what's going on here. Any of your inputs are appreciated!
因为如果我写下面的分组完全有效;
Because If I write the below grouping is completely valid;
Map<Integer,List<Student>> m = students.stream().
collect(Collectors.groupingBy(Student::getMarks));
这是我的Student.java类(如果需要的话)
Here is my Student.java class (In case if you need it)
public class Student {
private String name;
private int marks;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
@Override
public String toString() {
return name + ':' + marks ;
}
}
推荐答案
不幸的是,当涉及方法引用时,错误消息非静态方法不能从静态上下文引用。只是任何类型不匹配问题的占位符。编译器根本无法确定实际问题。
Unfortunately, the error message "Non-static method cannot be refered from a static context." is just a place-holder for any type mismatch problem, when method references are involved. The compiler simply failed to determine the actual problem.
在您的代码中,目标类型 Map< Integer,Map< String,List< String> >>
与合并收藏家的结果类型不匹配,即地图<整数,列表< String>>
,但是编译器没有尝试确定此(独立)结果类型,因为包含方法引用的(嵌套)泛型方法调用需要用于解析方法引用的目标类型。所以它不报告赋值的类型不匹配,但是解决方法引用的问题。
In your code, the target type Map<Integer, Map<String, List<String>>>
doesn’t match the result type of the combined collector which is Map<Integer, List<String>>
, but the compiler didn’t try to determine this (stand-alone) result type, as the (nested) generic method invocations incorporating method references requires the target type for resolving the method references. So it doesn’t report a type mismatch of the assignment, but a problem with resolving the method references.
正确的代码只是
Map<Integer, List<String>> groupping = students.stream()
.collect(Collectors.groupingBy(Student::getMarks,
Collectors.mapping(Student::getName, Collectors.toList())));
这篇关于静态上下文无法访问收集器中的非静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!