Search code examples
javahashmaplinkedhashmapgroupingby

Java 8 groupingBy to obtain LinkedHashMap and mapping the values of the map to a different object


I have this method which returns a Map:

    public Map<String, List<ResourceManagementDTO>> getAccountsByGroupNameMap(final List<AccountManagement> accountManagementList) {
    
    return new LinkedHashMap<>(accountManagementList.stream().collect(Collectors.groupingBy(acc -> acc.getGroup().getName(),
            Collectors.mapping(ResourceManagementDTOMapper::toResourceManagementDTO, Collectors.toList()))));
}

I need my map to be a LinkedHaspMap, but the above code doesn't seem to work, because the order of the keys isn't preserved. I managed to find another approach which would return a LinkedHashMap, however with that syntax I wasn't able to do the mapping operation anymore (to map AccountManagement to ResourceManagementDTO). Here's the code:

    public Map<String, List<AccountManagement>> getAccountsByGroupNameMap(final List<AccountManagement> accountManagementList) {
    return accountManagementList.stream()
                                 .collect(groupingBy(acc -> acc.getGroup().getName(), LinkedHashMap::new, Collectors.toList()));
}

Is there a way to get the LinkedHashMap and also perform the mapping operation in a single Java 8 pipeline? I really couldn't figure an syntax that combines both operations.


Solution

  • Try the following: groupingBy takes a supplier for the map type.

    public Map<String, List<ResourceManagementDTO>>
                getAccountsByGroupNameMap(
                        final List<AccountManagement> accountManagementList) {
            
            return accountManagementList.stream()
                    .collect(Collectors.groupingBy(
                            acc -> acc.getGroup().getName(),
                            LinkedHashMap::new,
                            Collectors.mapping(
                                    ResourceManagementDTOMapper::toResourceManagementDTO,
                                    Collectors.toList())));