Static context cannot access non-stationary in collectors

I have a group of students. First I want to group them by tags. Then I want to further group these groups into the same name together.

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

I get an error message

A non-static method cannot refer to a static context.

Yes. I pretty much understand that I cannot reference a non-static method without an instance. But with all these streaming operations, I'm a little confused about what went wrong.

Instead of fixing it; I really want to know what is going on here. Any of your entries are appreciated!

Because if I write, the grouping below is completely correct;

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

Here is my Student.java class (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 ; } } 
+7
java-8 java-stream method-reference collect
source share
2 answers

Unfortunately, the error message "Non-static method cannot be referenced in a static context." is simply the owner of the site for any type of mismatch problem when method references are involved. The compiler simply could not determine the actual problem.

In your code, the target type Map<Integer, Map<String, List<String>>> does not match the result type of the unified collector, which is Map<Integer, List<String>> , but the compiler did not try to determine this (stand-alone) result type, how (nested) generic method calls involving method references require a target type to resolve method references. Therefore, it does not report a mismatch in the type of destination, but a problem with resolving method references.

The right code is just

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

I think Holger gave a good explanation of the error and why it does not make much sense in one run.

Given 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 will just give you a list of students, first grouped by tags, and then by name. :))

+1
source share

All Articles