user3400060
user3400060

Reputation: 309

Keys mapping to same values in HashMap?

As the title tells,I have to write a method to say true if 2 string keys in a map do not have same string values and false otherwise.I have written the following method.However, it returns true in all cases.A suggestion here will help.

public static boolean isUnique(Map<String,String> map)
    {
        Iterator<String> iter=map.keySet().iterator();
        while(iter.hasNext())
        {
            String s=iter.next();
            if(map.containsValue(s))
                return false;
        }
        return true;
    }

Thanks in advance

Upvotes: 0

Views: 79

Answers (1)

Boann
Boann

Reputation: 50061

The easiest way is to put the values into a set. Since a set cannot contain duplicate values, if the size of the set equals the size of the map, then the map does not contain any duplicate values.

public static boolean areValuesUnique(Map<?,?> map) {
    return new HashSet<>(map.values()).size() == map.size();
}

Upvotes: 6

Related Questions