NoobEditor
NoobEditor

Reputation: 15871

check if hashmap contains value other than certain value

I am trying to implement HashMap in JAVA, in my algorithm, i have to find if any of the keys contain values other than a specific value....for instance, lets say, all the keys in the map should have value 0 stored in them.

How can i check if, the map contains value which is not equal to 0.

I tried this but logically it isn't correct i know :

if(!hm.containsValue(0)) /* where hm is hashmap object*/

Upvotes: 2

Views: 12640

Answers (2)

Manoj Shrestha
Manoj Shrestha

Reputation: 4684

you can define the map as follows:

Map<String, Integer> map = new HashMap<String, Integer>();

And check if it contains a non-zero value as follows :

    for ( Integer value: map.values()) {
        if ( value != 0) {
            // non-zero value found in the map
        }
    }

Upvotes: 2

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

You have to iterate over all the values and check each one to see if it's not equal to zero, and that's O(n). There's no alternative using a Map, a Map is efficient for finding keys, not for finding something in the values. For example, using the standard Map implementation in Java:

Integer zero = new Integer(0);
for (Integer i : hm.values()) {
    if (!zero.equals(i)) {
        System.out.println("found one non-zero value");
        break;
    }
}

Upvotes: 3

Related Questions