开发者

How to swap two keys in a map

开发者 https://www.devze.com 2023-02-05 00:52 出处:网络
Is there a way to swap two keys in a map in Java? ex. for list there is Collections.swap(ArrayList,1,开发者_高级运维2);You can use this one liner:

Is there a way to swap two keys in a map in Java?

ex. for list there is Collections.swap(ArrayList,1,开发者_高级运维2);


You can use this one liner:

map.put('a', map.put('b', map.get('a')));


If you need to handle boundary cases, like one of the keys not actually being in the map, you can do something like this:

public static <K,V> void swap(Map<K, V> map, K k1, K k2) {
    if (map.containsKey(k1)){
        if (map.containsKey(k2)){
            map.put(k1, map.put(k2, map.get(k1)));
        } else {
            map.put(k2, map.remove(k1));
        }
    } else if (map.containsKey(k2)){
        map.put(k1, map.remove(k2));
    }
}

Otherwise, use the on-liner in Abdullah Jibaly's answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消