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 Student
s:
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 Student
s 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.