首页 文章

交换两个地图的值

提问于
浏览
0

我是初学者,我想通过使用两个旧地图 hm1 和 hm2 创建一个新地图 hm3,并且在该地图中我需要第二个地图的值作为键和第一个地图的值作为值例如:如果地图 hm1 包含 a1 作为 key1 和 abc 作为 value1,它还包含 a2 作为 key2,xyz 作为 value2,还有另一个映射 hm2,其中包含 a1 作为 key1,b1 作为 value1,并且还包含 a2 作为 key2,b2 作为 value2 然后在地图 hm3 中我需要 b1 作为 key1,abc 作为 value1,b2 作为 key2,xyz 作为 value2

public class MapInterchange {

    public static void main(String[] args) {

        HashMap<String, String> hm1 = new HashMap<String, String>();
        Map.Entry m1;
        hm1.put("a1", "abc");
        hm1.put("a2", "xyz");

        for (Map.Entry m : hm1.entrySet()) {
            System.out.println(m.getKey() + " " + m.getValue());
        }

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

        hm2.put("a1", "b1");
        hm2.put("a2", "b2");

        for (Map.Entry m : hm2.entrySet()) {
            System.out.println(m.getKey() + " " + m.getValue());
        }

        HashMap<Object, Object> hm3 = new HashMap<Object, Object>();

        Iterator itr = ((Set<Entry<String, String>>) hm1).iterator();
        while (itr.hasNext()) {
            hm3.put(((Entry) hm2).getValue(), ((Entry) hm1).getValue());
        }

        for (Map.Entry m : hm3.entrySet()) {
            System.out.println(m.getKey() + " " + m.getValue());
        }

     }

    }

The exception I'm getting is : Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Set
    at com.sid.MapInterchange.main(MapInterchange.java:34)

请提供更正后的代码,我将非常感谢

1 回答

  • 1

    您不能将 HashMap 强制转换为一组条目。使用entrySet方法。

    Iterator<Map.Entry<String,String>> itr = hm1.entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String,String> entry = itr.next();
        hm3.put(entry.getKey(), entry.getValue());
    }
    

    编辑:我不确定这段代码是否符合您的要求,但它克服了您的错误。目前尚不清楚你要交换什么。

    如果值的映射基于键,则代码应为:

    Iterator<Map.Entry<String,String>> itr = hm1.entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String,String> entry = itr.next();
        hm3.put(hm2.get(entry.getKey()), entry.getValue());
    }
    

    这假设hm1的所有键都出现在hm2中(否则你的输出 Map 中会有一个null键)。

相关问题