Search code examples
javalistdictionaryhashmap

How to retrieve a collection of values from a HashMap


I'm writing a function to test if a HashMap has null values. The method .values() SHOULD return a collection of just the values, but instead I receive a map with both the keys and values stored inside. This is no good as the purpose of my function is to check if the values are null, but if I return a map with keys AND values then .values().isEmpty() returns false if I have a key stored with no value.

  public Map<KEY, List<VALUES>> methodName() {
    if (MAPNAME.values().isEmpty()) {
            throw new CustomErrorException(ExceptionHandler.getErrorWithDescription(ErrorConstants.ERROR_MSG_01));
        } else {
            return MAPNAME;
        }
    }

In the above example, .values() always returns a map containing all the keys and values. My method never throws a CustomErrorException if the HashMap has a key, which is bad since it's supposed to detect if there are no values. Help!


Solution

  • There's no such thing as a Map implementation that has a key stored without a value. All Map implementations either:

    • throw an exception in put when the value is null
    • Add an entry with a key and a value of null

    A key that maps to null is very different than a key without a value. The key has a value, and that value is null (and that means that the values collection won't be empty, unless the map is empty). A key without a value is a key that's not contained in the map.

    Long story short, you probably want to use MAPNAME.values().contains(null) or even just MAPNAME.containsValue(null) to do what you want. Alternatively, if you're checking that every key maps to null, check that by iterating over the .values() collection.