You need to enable JavaScript to run this app. Java 8 Stream:如何用groupingBy将Map<String,List<Integer>>转为Map<Integer,List<String>>
优惠活动
大模型
产品
解决方案
定价
更多

Java 8 Stream:如何用groupingBy将Map<String,List<Integer>>转为Map<Integer,List<String>>

实现方案

核心代码

import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// 核心分组逻辑
Map<Integer, List<String>> pincodeToCities = cityMap.entrySet().stream()
        .flatMap(cityEntry -> cityEntry.getValue().stream()
                .map(pincode -> new AbstractMap.SimpleEntry<>(pincode, cityEntry.getKey()))
        )
        .collect(Collectors.groupingBy(
                Map.Entry::getKey,
                Collectors.mapping(Map.Entry::getValue, Collectors.toList())
        ));

输出验证

上述代码执行后得到的pincodeToCities结构和预期完全一致:

{1=[city1, city2], 2=[city1, city3], 3=[city1, city2, city3], 4=[city2], 5=[city2, city3], 6=[city3], 7=[city3]}

内容的提问来源于stack exchange,提问作者Lalit Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 00:33:03