Java 你能帮我合并几个地图的值吗?

Java 你能帮我合并几个地图的值吗?,java,java-8,hashmap,java-stream,collectors,Java,Java 8,Hashmap,Java Stream,Collectors,我正在尝试进行以下修改: final Map<String, List<Map<String, String>>> scopes = scopeService.fetchAndCacheScopesDetails(); final Map<String, Map<String, String>> scopesResponse = scopes.entrySet().stream().collect (Collectors

我正在尝试进行以下修改:

final Map<String, List<Map<String, String>>> scopes = scopeService.fetchAndCacheScopesDetails();
final Map<String, Map<String, String>> scopesResponse = scopes.entrySet().stream().collect
        (Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
                .stream().collect(Collectors.toMap(s -> (String) s.get(SCOPE_NM), s -> (String) s.get(SCOPE_ID))))
        );
final Map scopes=scopeService.fetchAndCacheScopesDetails();
最终映射范围响应=scopes.entrySet().stream().collect
(Collectors.toMap(Map.Entry::getKey,e->e.getValue()
.stream().collect(Collectors.toMap(s->(String)s.get(SCOPE\u NM),s->(String)s.get(SCOPE\u ID)))
);
但是我面临
“复制键”
错误,所以我想将
范围响应更改为
映射


在这种情况下,您能告诉我如何将值
s->(String)s.get(SCOPE_ID)
合并到
列表或
集合中吗?

您需要为内部
映射的值创建一个
集合,并提供一个合并功能:

final Map<String, Map<String, Set<String>>> scopesResponse = scopes.entrySet().stream().collect
    (Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
            .stream().collect(Collectors.toMap(s -> s.get(SCOPE_NM),
                                               s -> {Set<String> set= new HashSet<>(); set.add(s.get(SCOPE_ID)); return set;},
                                               (s1,s2)->{s1.addAll(s2);return s1;}))));
您也可以使用的(multimap类似于列表的映射):

Map scopesResponse=scopes.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,e->toMultimap(e));
在哪里

静态ImmutableListMultimap到MultiMap(
地图(输入){
返回条目.getValue().stream().collect(ImmutableListMultimap.toImmutableListMultimap(
s->(字符串)s.get(范围\u NM),
s->(字符串)s.get(作用域ID)
));
}
如果列表中的值被证明是重复的,并且您不希望重复,请使用

final Map<String, Map<String, Set<String>>> scopesResponse2 = scopes.entrySet().stream().collect
    (Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
            .stream().collect(Collectors.groupingBy(s -> s.get(SCOPE_NM),
                                               Collectors.mapping(s -> s.get(SCOPE_ID),Collectors.toSet())))));
Map<String, ListMultimap<String, String>> scopesResponse = scopes.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> toMultimap(e)));
static ImmutableListMultimap<String, String> toMultimap(
        Map.Entry<String, List<Map<String, String>>> entry) {
    return entry.getValue().stream().collect(ImmutableListMultimap.toImmutableListMultimap(
            s -> (String) s.get(SCOPE_NM),
            s -> (String) s.get(SCOPE_ID)
    ));
}