在Java中以递归方式交换嵌套映射的键和值

时间:2018-01-19 13:46:22

标签: java algorithm recursion hashmap swap

如何在Java中编写一个递归方法,该方法接受嵌套映射并交换键及其值。但由于它是嵌套映射,因此键或值也可以是映射,如果是这种情况,也应该交换它。到目前为止我只得到了这个:

public class MyRekursion {
    public static <K, V> HashMap<V, K> deepReverseMap(Map<K, V> nestedMap) {
        HashMap<V, K> rev = new HashMap<V, K>();

        for (Map.Entry<K, V> entry : nestedMap.entrySet()){
            K key = entry.getKey();
            V val = entry.getValue();
            if (key instanceof Map){
                // ???
                // key = (K)deepReverseMap((Map<K, V>)key);
            }
            if (val instanceof Map){
                // ???
                // val = (V)deepReverseMap((Map<K, V>)val);
            }
            rev.put(val, key);
        }

    return rev;
    }
}

将deepReverseMap()的返回值强制转换为K或V可能是错误的。如何正确编写此方法?

2 个答案:

答案 0 :(得分:1)

如果您删除评论,您提出的代码似乎有效。我建议在这些方面写一些代码以简洁:

public static <K, V> HashMap<V, K> deepReverseMap(Map<K, V> nestedMap) {
    HashMap<V, K> rev = new HashMap<>();

    for (Map.Entry<K, V> entry : nestedMap.entrySet()) {
        K key = entry.getKey();
        V val = entry.getValue();
        rev.put(val instanceof Map ? (V) deepReverseMap((Map<K, V>) val) : val,
                key instanceof Map ? (K) deepReverseMap((Map<K, V>) key) : key);
    }
    return rev;
}

或使用流:

public static <K, V> HashMap<V, K> deepReverseMap(Map<K, V> nestedMap) {
    return nestedMap.entrySet().stream().collect(HashMap::new, (m, e) -> {
        final K key = e.getKey();
        final V val = e.getValue();
        m.put(Map.class.isInstance(val) ? (V) deepReverseMap((Map<K, V>) val) : val,
                Map.class.isInstance(key) ? (K) deepReverseMap((Map<K, V>) key) : key);
    }, (k, v) -> {});
}

你无法避免未经检查的演员阵容。

这是一个简单的测试:

public static void main(String[] args) {
    Map<Integer, Map<String, Integer>> m = new HashMap<>();

    Map<String, Integer> m1 = new HashMap<>();
    m1.put("s1", 1);
    m.put(1, m1);

    Map<String, Integer> m2 = new HashMap<>();
    m2.put("s2", 2);
    m.put(2, m2);

    Map<String, Integer> m3 = new HashMap<>();
    m3.put("s3", 3);
    m3.put("s3_1", 31);
    m.put(3, m3);
    System.out.println(m);

    Map<Map<String, Integer>, Integer> res = deepReverseMap(m);
    System.out.println(res);
}

此测试也会反转嵌套地图中的键和值:

{1={s1=1}, 2={s2=2}, 3={s3=3, s3_1=31}}
{{3=s3, 31=s3_1}=3, {2=s2}=2, {1=s1}=1}

答案 1 :(得分:0)

在Java中没有类型安全的方法,你需要使用未经检查的强制转换:

if (key instanceof Map){
    key = (K) deepReverseMap((Map<?, ?>)key);
}
if (val instanceof Map){
    val = (V) deepReverseMap((Map<?, ?>)val);
}