检索具有相同值的所有地图键

时间:2019-06-08 10:11:45

标签: java

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

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));

    }
}

2 个答案:

答案 0 :(得分:1)

getKeys返回一个Set<K>,这意味着在字符串操作中遇到Set#toString之类的表达式时,将使用hashMap.getKeys(1)Set#toString添加了这些提示。

您可能想研究String.join

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

答案 1 :(得分:0)

只需添加另一种与流相反的方式并使用Apache StringUtils以所需的格式打印输出即可。

Map<Object, List<Object>> reversedDataMap = inputDataMap.entrySet().stream().collect(
    Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));

// read the value-key map and print
reversedDataMap
    .forEach((k, v) -> System.out.printf("For key %d values are %s \n", k, StringUtils.join(v, " ")));
相关问题