作者:mobiledu2502905463 | 来源:互联网 | 2022-11-30 16:19
我正在尝试进行以下修改:
final Map>> scopes = scopeService.fetchAndCacheScopesDetails();
final Map> 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))))
);
但我面临"Duplicate key"
错误,所以我想scopeResponses
改为Map>>
你能告诉我如何将值合并s -> (String) s.get(SCOPE_ID)
到一个List
或Set
在这种情况下?
1> Eran..:
您需要为Set
inner的值创建一个Map
,并提供合并函数:
final Map>> scopesRespOnse= scopes.entrySet().stream().collect
(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
.stream().collect(Collectors.toMap(s -> s.get(SCOPE_NM),
s -> {Set set= new HashSet<>(); set.add(s.get(SCOPE_ID)); return set;},
(s1,s2)->{s1.addAll(s2);return s1;}))));
或者,你可以构造内Map
有groupingBy
:
final Map>> 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())))));