在Hashmap中交换行和键

时间:2018-04-23 09:03:47

标签: java hashmap

我正在寻找一种重新排序散列图的方法......类似于使用各自的密钥交换两行hashmap ...

我的hashmap就像交换之前一样

["key1","value1"];
["key2","value2"];
["key3","value3"];
["key4","value4"];

交换密钥1和密钥2后,​​

["key4","value4"];
["key2","value2"];
["key3","value3"];
["key1","value1"];

我想将两行与密钥交换。是否可以在java中使用?

2 个答案:

答案 0 :(得分:0)

哈希映射不可能。 HashMap并不保证订购。为此,请查看LinkedHashMap

LinkedHashMap

交换
    LinkedHashMap<String, String> oldMap = new LinkedHashMap<>();
    oldMap.put("key1", "value1");
    oldMap.put("key2", "value2");
    oldMap.put("key3", "value3");
    oldMap.put("key4", "value4");
    System.out.println(oldMap);

    ArrayList<String> keySetList = new ArrayList<>();
    keySetList.addAll(oldMap.keySet());

    Collections.swap(keySetList, 0, 3);

    // our output map
    LinkedHashMap<String, String> swappedMap = new LinkedHashMap<>();

    for(String oldSwappedKey:keySetList) {
        swappedMap.put(oldSwappedKey, oldMap.get(oldSwappedKey));
    }

    System.out.println(swappedMap);

交换14

Input map:{key1=value1, key2=value2, key3=value3, key4=value4}
Output map:{key4=value4, key2=value2, key3=value3, key1=value1}

答案 1 :(得分:0)

也许是这样的?参数化键,但这应该结束&#34;交换&#34; key1和key2后面的值。

private void test(HashMap<MyKey, MyValue> map) {
    Set<MyKey> keyset = map.keySet();
    MyKey key1 = keyset.get(0);
    MyKey key2 = keyset.get(1);

    MyValue val1;
    MyValue val2;

    if (map.containsKey(key1)) {
        val1 = map.get(key1);
    }

    if (map.containsKey(key2)) {
        val2 = map.get(key2);
    }

    if (val2 != null)
    map.put(key1, val2);
    if (val1 != null)
    map.put(key2, val1);
}