Group a list of objects by an attribute
Tutorial by Er Satya
All > Tech Blogger | Java | Spring Boot | HTML | CSS | MySQL > Java | Spring Boot
1 like
Please login to like this article.
HashMap
with locationID
as key.HashMap> hashMap = new HashMap
>>();
HashMap
:if (!hashMap.containsKey(locationId)) {
List list = new ArrayList >();
list.add(employee );
hashMap.put(locationId, list);
} else {
hashMap.get(locationId).add(employee );
}
hashMap.get(locationId);
which will get you all the employee with the same the location ID.
Java 8 groupingBy Collector
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 questionMapEmployee
>> map = groupBy(employee list, Employee::getLocation);
More articles from same author:
More articles:
Recent lost & found:
Login for enhanced experience
Create and manage your profile
Refer an author and get bonus Learn more
Publish any lost and found belongings
Connect with the authors & add your review comments
Join us for Free to advertise for your business or Contact-us for more details
Join us for Free to publish your own blogs, articles or tutorials and get your Benefits
Discover your area of interest
Advertisement
Art & entertainment
Astrology & spirituality
Cooking
Culture
Current affairs
Education
Fashion
History
Hotel management
Industry
Medical & fitness
Motivational
Politics
Real life stories
Sports
Story & poetry
Technology
Top in search
Tourism
More recent categories
CEMAC Buyer Permit, CEMAC Permit, or Mandate License.(Public)
By: CEMAC
Regulation For Importing Africa Gold Into The U.S.: EUROPE: DUBAI Coins, Medals, and?Bullion(Public)
By: CEMAC
CEMAC PERMIT APPLICATION FORM ATTACHED(Public)
By: CEMAC
Ministry of Mines Cameroon Scam(Public)
By: CEMAC
How To Import Gold Dore Bars from West and Central Africa(Public)
By: CEMAC
Exclusive Gold Offers: 500 KG Gold Bars(Public)
By: CEMAC
How to Buy Certified Gold Bars Safely(Public)
By: CEMAC
Gold for Sale Near You(Public)
By: CEMAC
Importing Gold from Cameroon To The US(Public)
By: CEMAC
CEMAC BUYERS PERMIT-CEMAC Trade & Business(Public)
By: CEMAC