如何将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
相关产品推荐
相关产品推荐

