Advertisements
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));