使用值交换键,反之亦然HashMap

时间:2016-07-26 12:25:19

标签: java hashmap

这是一个启动性问题,我想用值交换键,反之亦然HashMap。这是我到目前为止所做的尝试。

import java.util.HashMap;
import java.util.Map;

class Swap{
    public static void main(String args[]){

        HashMap<Integer, String> s = new HashMap<Integer, String>();

        s.put(4, "Value1");
        s.put(5, "Value2");

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

2 个答案:

答案 0 :(得分:6)

您需要一个新的Map,因为示例中的键和值有不同的类型。

在Java 8中,通过创建原始Stream的{​​{1}}条目并使用Map toMap生成新的{{}},可以非常轻松地完成此操作1}}:

Collector

答案 1 :(得分:1)

正如Eran所建议的,我编写了一个简单的演示来将hashmap的键和值与另一个hashmap交换。

import java.util.HashMap;
import java.util.Map;

class Swap {
    public static void main(String args[]) {

        HashMap<Integer, String> s = new HashMap<Integer, String>();

        s.put(4, "Value1");
        s.put(5, "Value2");

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

        /*
         * swap goes here
         */
        HashMap<String, Integer> newMap = new HashMap<String, Integer>();
        for(Map.Entry<Integer, String> entry: s.entrySet()){
            newMap.put(entry.getValue(), entry.getKey());
        }

        for(Map.Entry<String, Integer> entry: newMap.entrySet()){
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}