Java, the fastest way to determine if any values ​​in a hashmap match a value?

Change my newbie to Java as I am not experienced enough to find out the most efficient way to do this. I have a hashmap as shown below, but it would have 40,000 entries:

Map <String, String> someHashmap = new HashMap <String, String> ();
someHashmap.put("filepath1", null);
someHashmap.put("filepath2", "tag1");
someHashmap.put("filepath3", "tag2");

I want to determine how many values ​​match nullso that I can determine if they are zeros. Of course, I could do a regular loop to check, but I wonder if there is a more efficient way, thanks

+5
source share
4 answers

You can use a method containsValuethat states:

true, .

somHashmap.containsValue(null);

, (, , ), , , O (1) , O ( n), .

+12

, .

HashMap a. HashMap<String, Integer> aCount. aCount .

, k v HashMap, , aCount.containsKey(v). , : aCount.put(v, aCount.get(v) + 1). : aCount.put(v, 1).

, k v HashMap, , aCount.get(v). , aCount.put(v, aCount.get(v) - 1) . (.. ) aCount.remove(v).

aCount.contains(v), , HashMap a.

? , , , O (n), , HashMap, O (1). , . , .

+4

, HashSet, HashMap. ( !).

public class MapWithVals<K, V> extends HashMap<K, V> {

    protected final Set<V> vals = new HashSet<V>();

    public MapWithVals() {
        super();
    }

    public MapWithVals(Map<? extends K, ? extends V> m) {
        super(m);
        vals.addAll(m.values());
    }

    @Override
    public void clear() {
        super.clear();
        vals.clear();
    }

    @Override
    public V put(K arg0, V arg1) {
        vals.add(arg1);
        return super.put(arg0, arg1);
    }


    @Override
    public V remove(Object arg0) {
        V val = get(arg0);
        super.remove(arg0);
        if( ! super.containsValue(val) ) vals.remove(val);
        return val;
    }

    @Override
    public boolean containsValue(Object value) {
        return vals.contains(value);
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> arg0) {
        super.putAll(arg0);
        vals.addAll(arg0.values());
    }

    @Override
    public Object clone() {
        throw new RuntimeException("not implemented");
    }

}
0

null, , put HashMap, , null key HashSet.

CRUD Map ↔ HashSet

0

All Articles