首页 > 解决方案 > 检索具有相同值的所有映射键

问题描述

我正在检索具有相同值的所有映射键。此代码给出正确的输出“[A,B]”。但我希望答案为 A B。如何更改代码以将输出作为 AB?

class MyHashMap<K, V> extends HashMap<K, V> {

    Map<V, Set<K>> reverseMap = new HashMap<>();
    public V put(K key, V value) {
        if (reverseMap.get(value) == null)
            reverseMap.put(value, new HashSet<K>());

        reverseMap.get(value).add(key);
        return super.put(key, value);
    }

    public Set<K> getKeys(V value) {
        return reverseMap.get(value);
    }

}

class Main
{
    public static void main(String[] args) {
        MyHashMap<String, Integer> hashMap = new MyHashMap();
        hashMap.put("A", 1);
        hashMap.put("B", 1);
        hashMap.put("C", 2);
        System.out.println("Gift is for "+hashMap.getKeys(1));

    }
}

标签: java

解决方案


getKeys当在字符串操作中遇到类似的表达式时,将使用返回一个Set<K>含义。添加这些刹车。Set#toStringhashMap.getKeys(1)Set#toString

你可能想调查一下String.join

System.out.println("Gift is for " + String.join(" ", hashMap.getKeys(1)));

推荐阅读