Lluis Martinez
Lluis Martinez

Reputation: 1973

Check if all values in a map are equal

I need to check if all values in a map are equal. I have a method to perform this task but would like to use a library or native methods. Limitations: Java 5 + Apache Commons libraries.

public static boolean isUnique(Map<Dboid,?> aMap){

boolean isUnique = true;
Object currValue = null;
int iteration = 0;

Iterator<?> it = aMap.entrySet().iterator();

while(it.hasNext() && isUnique){
    iteration++;
    Object value = it.next();
    if(iteration > 1){
        if (value != null && currValue == null ||
            value == null && currValue != null ||
            value != null && currValue != null & !value.equals(currValue)) {
            isUnique = false;
        }
    }
    currValue = value;
}
return isUnique;
}

Upvotes: 4

Views: 22251

Answers (6)

Justin Gottshall
Justin Gottshall

Reputation: 131

I know the original questions asks for solutions in Java 5, but in case someone else searching for an answer to this question is not limited to Java 5 here is a Java 8 approach.

return aMap.values().stream().distinct().limit(2).count() < 2

Upvotes: 2

nachokk
nachokk

Reputation: 14413

As my comment above:

//think in a more proper name isAllValuesAreUnique for example
    public static boolean isUnique(Map<Dboid,?> aMap){
         if(aMap == null)
               return true; // or throw IlegalArgumentException()

         Collection<?> c = aMap.getValues(); 
         return new HashSet<>(c).size() <= 1;
    }

Upvotes: 1

Meno Hochschild
Meno Hochschild

Reputation: 44061

public static boolean isUnique(Map<Dboid,?> aMap) {
    Set<Object> values = new HashSet<Object>();

    for (Map.Entry<Dboid,?> entry : aMap.entrySet()) {
      if (!values.isEmpty() && values.add(entry.getValue())) {
        return false;
      }
    }

    return true;
}

This solution has the advantage to offer a memory-saving short cut if there are many differences in the map. For the special case of an empty Map you might choose false as return value, change it appropriately for your purpose.

Or even better without a Set (if your Map does not contain null-values):

public static boolean isUnique(Map<Dboid,?> aMap) {
    Object value = null;

    for (Object entry : aMap.values()) {
      if (value == null) {
        value = entry;
      } else if (!value.equals(entry)) {
        return false;
      }
    }

    return true;
}

Upvotes: 1

David Ehrmann
David Ehrmann

Reputation: 7576

You could store the values in a Bidirectional Map and always have this property.

Upvotes: 1

Abhijeet Kushe
Abhijeet Kushe

Reputation: 2597

how about

return (new HashSet(aMap.values()).size() == 1)

Upvotes: 2

user330315
user330315

Reputation:

What about this something like this:

Set<String> values = new HashSet<String>(aMap.values());
boolean isUnique = values.size() == 1;

Upvotes: 15

Related Questions