Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Most efficient way to create a hash map from a list of objects – with the object field as key?

I have the following Java 8 code:

final Person[] personEntities = personRepository.getPersons(groupIds);
    
Map<String, List<Person>> personMapByDepartmentId = new HashMap<>();

for (Person person: personEntities ) {
    // create hashmap:departmentId as the key, and person entities as the value
}

Person object is a standard POJO with fields Id, Name and departmentId

What is the best way to do the above, is HashMap the most efficient?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Collectors.groupingBy.

Map<String, List<Person>> personMapByDepartmentId = Arrays.stream(personEntities)
   .collect(Collectors.groupingBy(Person::getDeparmentId));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading