开发者社区> 问答> 正文

反转地图 值--->键

我希望能够逆转具有多个键的给定HashMap可以指向相同的值。

HashMap<String, String> cities = new HashMap<String, String>();

        cities.put("Manchester", "UK");
        cities.put("London", "UK");
static HashMap<String, String> inverseMap(HashMap map) {
       // something that has "UK" point to both "Manchester" and "London"

      // if it can be done without using any special Java 8 feature, that would be great
}

我不确定从哪里开始。

问题来源:Stack Overflow

展开
收起
montos 2020-03-21 22:14:26 944 0
1 条回答
写回答
取消 提交回答
  • 像这样做。基本上,它使用合并功能来合并重复键的值。 - 建立新地图 - 使用旧地图的值作为新地图的键 - 如果新地图没有键的值,则将值放在新地图中 - 否则,将值连接到该键的旧值

    HashMap<String, String> cities = new HashMap<String, String>();
    
            cities.put("Manchester", "UK");
            cities.put("London", "UK");
            cities.put("New York", "US");
            cities.put("Chicago", "US");
    
            Map<String,String> inverted = new HashMap<>();
            for (String key : cities.keySet()) {
                String newKey = cities.get(key);
                String value = inverted.get(newKey);
                if (value == null) {
                    inverted.put(newKey, key);
                } else {
                    value = value + ", " + key;
                    inverted.put(newKey, value);
                }
    
            }
            for (Entry<String,String> e : inverted.entrySet()) {
                System.out.println(e.getKey() + " -> " + e.getValue());
            }
    

    它打印

    UK -> Manchester, London
    US -> New York, Chicago
    

    由于您未指定如何处理重复键。我也可以将其存储在Map<String,List >

    回答来源:Stack Overflow

    2020-03-21 22:15:54
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载