Check if all values in a map are equal

后端 未结 6 1182
一生所求
一生所求 2021-01-15 03:37

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 Common

相关标签:
6条回答
  • 2021-01-15 03:51
    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;
    }
    
    0 讨论(0)
  • 2021-01-15 03:51

    how about

    return (new HashSet(aMap.values()).size() == 1)
    
    0 讨论(0)
  • 2021-01-15 04:00

    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
    
    0 讨论(0)
  • 2021-01-15 04:08

    What about this something like this:

    Set<String> values = new HashSet<String>(aMap.values());
    boolean isUnique = values.size() == 1;
    
    0 讨论(0)
  • 2021-01-15 04:09

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

    0 讨论(0)
  • 2021-01-15 04:09

    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;
        }
    
    0 讨论(0)
提交回复
热议问题