I have class named Student and it has String attribute date. I have list of all my Students and now I want to create multiple ArrayLists which are grouped by their dates.
I want to use hashmap:
ArrayList students = getStudents();
Map map<String, ArrayList<Student>> = new HashMap<String, ArrayList<Student>);
for (Student i: students) {
// There must be something
}
How I can create multiple ArrayLists of Students which are grouped by their String value of their attribute?
The easiest way it to use Java 8 Streams :
Map<String, List<Student>> map =
students.stream()
.collect(Collectors.groupingBy(Student::getDate));
Where getDate is the method of Student class by which you wish to group the Students.
To complete the answer for pre-Java 8 code:
Map<String, List<Student>> map = new HashMap<>();
for (Student s : students) {
List<Student> list = map.get(s.getDate());
if (list == null) {
list = new ArrayList<Student>();
map.put (s.getDate(), list);
}
list.add (s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With