Java8GroupingBy获取linkedhashmap并将Map的值Map到不同的对象

wi3ka0sx  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(283)

我有一个返回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()))));
}

我需要我的Map是linkedhaspmap,但是上面的代码似乎不起作用,因为键的顺序没有保留。我设法找到了另一种返回linkedhashmap的方法,但是使用这种语法,我无法再执行Map操作(将accountmanagementMap到resourcemanagementdto)。代码如下:

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

有没有一种方法可以获取linkedhashmap并在单个Java8管道中执行Map操作?我真的想不出一个结合这两种操作的语法。

0tdrvxhp

0tdrvxhp1#

尝试以下操作:groupingby将供应商作为Map类型。

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

相关问题