Static context cannot access non-static in Collectors

本小妞迷上赌 提交于 2019-11-28 08:09:48

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.

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.

The correct code simply is

Map<Integer, List<String>> groupping = students.stream()
    .collect(Collectors.groupingBy(Student::getMarks, 
             Collectors.mapping(Student::getName, Collectors.toList())));

I think Holger has given a good explanation about the error and why it doesn't make much sense in one run.

Considering your goal, I think this is the solution you need to have.

 Map<Integer, Map<String, List<Student>>> grouping = students.stream().collect(Collectors.groupingBy(Student::getMarks,
                Collectors.groupingBy(Student::getName)));

This would simply give you a student list first grouped by marks, then by name. :))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!