I need to group a list of objects (Student
) using an attribute (Location
) of the particular object. The code is like below:
public class Grouping {
public static void main(String[] args) {
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
studlist.add(new Student("4321", "Max", "California"));
studlist.add(new Student("2234", "Andrew", "Los Angeles"));
studlist.add(new Student("5223", "Michael", "New York"));
studlist.add(new Student("7765", "Sam", "California"));
studlist.add(new Student("3442", "Mark", "New York"));
}
}
class Student {
String stud_id;
String stud_name;
String stud_location;
Student(String sid, String sname, String slocation) {
this.stud_id = sid;
this.stud_name = sname;
this.stud_location = slocation;
}
}
Please suggest me a clean way to do it.
This will add the students object to the HashMap
with locationID
as key.
HashMap<Integer, List<Student>> hashMap = new HashMap<Integer, List<Student>>();
Iterate over this code and add students to the HashMap
:
if (!hashMap.containsKey(locationId)) {
List<Student> list = new ArrayList<Student>();
list.add(student);
hashMap.put(locationId, list);
} else {
hashMap.get(locationId).add(student);
}
If you want all the student with particular location details then you can use this:
hashMap.get(locationId);
which will get you all the students with the same the location ID.