Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset all values in hashmap without iterating?

Tags:

java

hashmap

I am trying reset all values in a HashMap to some default value if a condition fails.

Currently i am doing this by iterating over all the keys and individually resetting the values.
Is there any possible way to set a same value to all the keys without iterating?

Something like:

hm.putAll("some val")  //hm is hashmap object
like image 341
NoobEditor Avatar asked Aug 29 '26 03:08

NoobEditor


1 Answers

You can't avoid iterating but if you're using java-8, you could use the replaceAll method which will do that for you.

Apply the specified function to each entry in this map, replacing each entry's value with the result of calling the function's Function#map method with the current entry's key and value.

m.replaceAll((k,v) -> yourDefaultValue);

Basically it iterates through each node of the table the map holds and affect the return value of the function for each value.

@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
    Node<K,V>[] tab;
    if (function == null)
        throw new NullPointerException();
    if (size > 0 && (tab = table) != null) {
        int mc = modCount;
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                e.value = function.apply(e.key, e.value); //<-- here
            }
        }
        if (modCount != mc)
            throw new ConcurrentModificationException();
    }
}

Example:

public static void main (String[] args){ 
    Map<String, Integer> m = new HashMap<>();
    m.put("1",1);
    m.put("2",2);

    System.out.println(m);
    m.replaceAll((k,v) -> null);
    System.out.println(m);
}

Output:

{1=1, 2=2}
{1=null, 2=null}
like image 51
Alexis C. Avatar answered Aug 31 '26 17:08

Alexis C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!