You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Map<Integer, List<String>>转换为Map<String, List<Integer>>

解决Map<Integer, List>到SortedMap<String, List>的转换问题

需求回顾

输入(已填充的Map):

1 = ["a", "b", "c"]
2 = ["a", "b", "z"]
3 = ["z"]

目标输出(有序Map):

a = [1, 2]
b = [1, 2]
c = [1]
z = [2,3]

原代码存在的问题

  • 第一个循环遍历的integers未定义,应该遍历原Map的键值对集合
  • 循环内integerListMap.put(i, strings)属于错误操作,原Map已填充数据,无需再次插入
  • 最后一个循环中distinctStrings.put(s, ???)是错误的,distinctStrings是List类型,没有put方法,应该操作目标stringListSortedMap

正确实现方法

方法一:普通循环实现(直观易读)

Map<Integer, List<String>> integerListMap; // 假设已填充数据
SortedMap<String, List<Integer>> stringListSortedMap = new TreeMap<>();

// 遍历原Map的每一组键值对
for (Map.Entry<Integer, List<String>> entry : integerListMap.entrySet()) {
    Integer numKey = entry.getKey();
    List<String> strList = entry.getValue();
    
    // 对每个字符串,将对应的整数key加入目标Map的列表中
    for (String str : strList) {
        // 若目标Map中无该字符串键,自动创建空列表,再添加整数
        stringListSortedMap.computeIfAbsent(str, k -> new ArrayList<>()).add(numKey);
    }
}

computeIfAbsent方法会自动处理键不存在的情况,无需手动判断,简化代码逻辑。

方法二:Stream流实现(简洁高效)

Map<Integer, List<String>> integerListMap; // 假设已填充数据
SortedMap<String, List<Integer>> stringListSortedMap = integerListMap.entrySet()
    .stream()
    // 将每个整数对应的字符串列表拆分为多个(字符串,整数)的键值对
    .flatMap(entry -> entry.getValue().stream()
        .map(str -> new AbstractMap.SimpleEntry<>(str, entry.getKey())))
    // 按字符串分组,用TreeMap保证有序,收集对应的整数列表
    .collect(Collectors.groupingBy(
        Map.Entry::getKey,
        TreeMap::new,
        Collectors.mapping(Map.Entry::getValue, Collectors.toList())
    ));

通过flatMap拆分原结构,再利用groupingBy直接完成分组和容器指定,代码更简洁。

内容的提问来源于stack exchange,提问作者Diogo Barroso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:50:29