Group a list of objects by an attribute
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.
Java 8 groupingBy Collector
Probably it's late but I like to share an improved idea to this problem. This is basically the same of @Vitalii Fedorenko's answer but more handly to play around.
You can just use the Collectors.groupingBy()
by passing the grouping logic as function parameter and you will get the splitted list with the key parameter mapping. Note that using Optional
is used to avoid the unwanted NPE when the provided list is null
public static <E, K> Map<K, List<E>> groupBy(List<E> list, Function<E, K> keyFunction) {
return Optional.ofNullable(list)
.orElseGet(ArrayList::new)
.stream()
.collect(Collectors.groupingBy(keyFunction));
}
Now you can groupBy anything with this. For the use case here in the question
Map<String, List<Student>> map = groupBy(studlist, Student::getLocation);
Maybe you would like to look into this also Guide to Java 8 groupingBy Collector
In Java 8:
Map<String, List<Student>> studlistGrouped =
studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
Map<String, List<Student>> map = new HashMap<String, List<Student>>();
for (Student student : studlist) {
String key = student.stud_location;
if(map.containsKey(key)){
List<Student> list = map.get(key);
list.add(student);
}else{
List<Student> list = new ArrayList<Student>();
list.add(student);
map.put(key, list);
}
}