0

I have a Student class. The structure of the class is:

class Student {
    
    String name;
    int age;
    String grade;
    
    //Getters and Setters

}

I have a List of such Students:

List<Student> students = new ArrayList<>();
//Populate the list with some instances of Student.

Now, for a particular business requirement, I need to get a Map<String, List<Student>> from the students List.

The "key" of the Map should be a value of the grade property of the Student class.

The "value" of the Map should be the List of all such Students having that grade.

For example,

If my students List is like this:

[{"Student1", 10, "A1"}, {"Student2", 12, "A2"}, {"Student3", 10, "A1"}, {"Student4", 11, "A1"}, {"Student5", 10, "A2"}, {"Student6", 10, "A1"}, {"Student7", 11, "B1"}]

I should get a Map like this:

{
    "A1" : [{"Student1", 10, "A1"}, {"Student3", 10, "A1"}, {"Student4", 11, "A1"}, {"Student6", 10, "A1"}],
    "A2" : [{"Student2", 12, "A2"}, {"Student5", 10, "A2"}],
    "B1" : [{"Student7", 11, "B1"}]
}

Please note that primarily I am looking for a solution using Java 8, while the older ways are also most welcome.

Mayank
  • 79
  • 6
  • 1
    the [documentation of `Collectors`](https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/stream/Collectors.html) has an example – user16320675 Apr 21 '22 at 06:10
  • All right, I got a simple solution. Thanks. ```Map> groupedMap = students.stream().collect(Collectors.groupingBy(Student::getGrade));``` – Mayank Apr 21 '22 at 06:33

0 Answers0