Harini
Harini

Reputation: 35

retrieve all map keys having a same value

I'm retrieving all map keys having a same value.This code give the correct output "[A,B]". But i want the answer as A B.How can i change the code to get the output as 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));

    }
}

Upvotes: 1

Views: 437

Answers (2)

TechFree
TechFree

Reputation: 2954

Just adding another way of reversing with streams & printing the output in the desired format using 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, " ")));

Upvotes: 0

Andrew
Andrew

Reputation: 49606

getKeys returns a Set<K> meaning Set#toString will be used when expressions like hashMap.getKeys(1) are encountered in string operations. Set#toString adds these brakets.

You may want to look into String.join.

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

Upvotes: 1

Related Questions