原谅我,如果该解决方案是非常明显的,但我似乎无法弄清楚如何做到这一点
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("b1", "a1");
map.put("b2", "a2");
map.put("b3", "a1");
Map<String, List<String>> mm = map.values().stream().collect(Collectors.groupingBy(m -> m));
System.out.println(mm);
}
我想通过组基于在HashMap中值。我想输出是{a1=[b1, b3], a2=[b2]}
,但它目前的来临{a1=[a1, a1], a2=[a2]}
目前,你流过映射值(我以为是一个错字),根据您所需的输出,你应该流过的地图entrySet
,并使用groupingBy
基于地图值的和mapping
基于地图键的下游收集器:
Map<String, List<String>> result = map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey,
Collectors.toList())));
你也可以不通过流执行这种逻辑forEach
+ computeIfAbsent
:
Map<String, List<String>> result = new HashMap<>();
map.forEach((k, v) -> result.computeIfAbsent(v, x -> new ArrayList<>()).add(k));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句