Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiple Array lists by using Hashmap

Tags:

java

arraylist

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?

like image 384
zxcdsa980 Avatar asked Sep 27 '26 10:09

zxcdsa980


1 Answers

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);
}
like image 191
Eran Avatar answered Sep 30 '26 01:09

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!