About us

Join us FREE!

Group a list of objects by an attribute

Tutorial by Er Satya connectclue-author-image

All > Tech Blogger | Java | Spring Boot | HTML | CSS | MySQL > Java | Spring Boot

1 like

Please login to like this article.

connectclue-linkedin-share

Group a list of objects by an attribute

This will add the employee object to the HashMap with locationID as key.
HashMap> hashMap = new HashMap>>();
Iterate over this code and add an employee to the HashMap:
if (!hashMap.containsKey(locationId)) {
    List list = new ArrayList >();
list.add(employee ); hashMap.put(locationId, list); } else { hashMap.get(locationId).add(employee ); }
If you want all the employee with particular location details then you can use this:
hashMap.get(locationId);
which will get you all the employee with the same the location ID.

Java 8 groupingBy Collector

You can just use the Collectors.groupingBy() bypassing the grouping logic as a function parameter and you will get the split list with the key parameter mapping. Note that using Optional is used to avoid unwanted NPE when the provided list is null

public static  Map> groupBy(List list, Function 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
MapEmployee>> map = groupBy(employee list, Employee::getLocation);


connectclue-linkedin-share

More articles:


Recent lost & found:


Login for enhanced experience

connectclue-tick Create and manage your profile

connectclue-tick Refer an author and get bonus Learn more

connectclue-tick Publish any lost and found belongings

connectclue-tick Connect with the authors & add your review comments

connectclue-tick Join us for Free to advertise for your business or Contact-us for more details

connectclue-tick Join us for Free to publish your own blogs, articles or tutorials and get your Benefits

connectclue-login

Back to top