Java 8 get List of attributes from List of objects

Group a list of objects by an attribute

In Java 8:

Map studlistGrouped = studlist.stream[].collect[Collectors.groupingBy[w -> w.stud_location]];

This will add the students object to the HashMap with locationID as key.

HashMap hashMap = new HashMap[];

Iterate over this code and add students to the HashMap:

if [!hashMap.containsKey[locationId]] { List list = new ArrayList[]; 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.


Map map = new HashMap[]; for [Student student : studlist] { String key = student.stud_location; if[map.containsKey[key]]{ List list = map.get[key]; list.add[student]; }else{ List list = new ArrayList[]; list.add[student]; map.put[key, list]; } }

Video liên quan

Chủ Đề