2

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.

elena A
  • 35
  • 1
  • 6

1 Answers1

1

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())));
WJS
  • 36,363
  • 4
  • 24
  • 39
  • 1
    Thanks, this worked. I think I was trying to do something similar, however my IDE kept showing error on acc,getGroup() saying it can't resolve method. – elena A Sep 04 '20 at 14:43
  • IDE's can be somewhat vague in their error messages. I use Eclipse and it can sometimes be difficult to figure out what the problem really is. – WJS Sep 04 '20 at 14:52