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?

>Solution :

You can use Collectors.groupingBy.

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

Leave a Reply