WeakHashMap class Methods in Java

java.util.WeakHashMap

Hash table-based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use.


Some methods of WeakHashMap class.


clear()This method removes all of the mappings from this map.


compute(K, BiFunction)This method attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).


computeIfAbsent(K, Function)If the specified key is not already associated with a value (or is mapped to null), attempt to compute its value using the given mapping function and enter it into this map unless null.


computeIfPresent(K, BiFunction)If the value for the specified key is present and non-null, attempt to compute a new mapping given the key and its current mapped value.


containsKey(Object)This method returns true if this map contains a mapping for the specified key.


containsValue(Object)This method returns true if this map maps one or more keys to the specified value.


entrySet()This method returns a Set view of the mappings contained in this map.


forEach(BiConsumer)This method performs the given action for each entry in this map until all entries have been processed or the action throws an exception.


get(Object)This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.


isEmpty()This method returns true if this map contains no key-value mappings.


keySet()This method returns a Set view of the keys contained in this map.


merge(K, V, BiFunction)If the specified key is not already associated with a value or is associated with null, associate it with the given non-null value.


put(K, V)This method associates the specified value with the specified key in this map.


putAll(Map)This method copies all of the mappings from the specified map to this map.


putIfAbsent(K, V)If the specified key is not already associated with a value associated with the given value and returns null, else returns the current value.


remove(Object)This method removes the mapping for a key from this weak hash map if it is present.


remove(Object, Object)This method removes the entry for the specified key only if it is currently mapped to the specified value.


replace(K, V)This method replaces the entry for the specified key only if it is currently mapped to some value.


replace(K, V, V)This method replaces the entry for the specified key only if currently mapped to the specified value.


replaceAll(BiFunction)This method replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.


size()This method returns the number of key-value mappings in this map.


values()This method returns a Collection view of the values contained in this map.


WeakHashMap values() in Java

values(): This method is available in java.util.WeakHashMap class in Java.

Syntax:

Collection<V> java.util.WeakHashMap.values()

This method returns a Collection view of the values contained in this map.

Note: The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

Parameters: NA

Returns: a collection view of the values contained in this map.

Exceptions: NA

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapvalues {
    public static void main(String[] args) {

        WeakHashMap<String, String> weakHashMap =
new WeakHashMap<String, String>();

        weakHashMap.put("Java", "Program");
        weakHashMap.put("Hello", "World");

        System.out.println(weakHashMap.values());

    }
}

Output:

[World, Program]


WeakHashMap size() in Java

size(): This method is available in java.util.WeakHashMap class of Java.

Syntax:

int java.util.WeakHashMap.size()

This method returns the number of key-value mappings in this map.

Parameters: NA

Returns: the number of key-value mappings in this map.

Exceptions: NA

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapsize {
    public static void main(String[] args) {

        WeakHashMap<String, String> weakHashMap =
new WeakHashMap<String, String>();

        weakHashMap.put("Java", "Program");
        weakHashMap.put("Hello", "World");

        System.out.println(weakHashMap.size());

    }
}

Output:

2


WeakHashMap replaceAll(BiFunction) in Java

replaceAll(BiFunction): This method is available in java.util.WeakHashMap class of Java.

Syntax:

void java.util.WeakHashMap.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

This method takes one argument. This method replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

Parameters: One parameter is required for this method.

function: the function to apply to each entry.

Returns: NA

Exceptions: NA

Approach

Java

import java.util.WeakHashMap;
import java.util.function.BiFunction;

public class WeakHashMapreplaceAll {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("1", 1);
        weakHashMap.put("2", 2);

        BiFunction<? super String, ? super Integer,
? extends Integer> function = (k, v) -> v +
Integer.parseInt(k);
        weakHashMap.replaceAll(function);
        System.out.println(weakHashMap);

    }
}

Output:

{1=2, 2=4}


WeakHashMap replace(K, V, V) in Java

replace(K, V, V): This method is available in java.util.WeakHashMap class of Java.

Syntax:

boolean java.util.Map.replace(K key, V oldValue, V newValue)

This method takes three arguments. This method replaces the entry for the specified key only if currently mapped to the specified value.

Parameters: Three parameters are required for this method.

key: key with which the specified value is associated.

oldValue: value expected to be associated with the specified key.

newValue: value to be associated with the specified key.

Returns: true if the value was replaced.

Throws:

1. UnsupportedOperationException - if the put operation is not supported by this map.

2. ClassCastException - if the class of a specified key or value prevents it from being stored in this map.

3. NullPointerException - if a specified key or newValue is null, and this map does not permit null keys or values.

4. IllegalArgumentException - if some property of a specified key or value prevents it from being stored in this map.

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapreplace2 {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        String key = "Java";
        Integer oldValue = 1, newValue = 3;

        System.out.println(weakHashMap.replace(key,
oldValue, newValue));

    }
}

Output:

true


WeakHashMap replace(K, V) in Java

replace(K, V): This method is available in java.util.WeakHashMap class of Java.

Syntax:

V java.util.Map.replace(K key, V value)

This method takes two arguments. This method replaces the entry for the specified key only if it is currently mapped to some value.

Parameters: Two parameters are required for this method.

key: key with which the specified value is associated.

value: value to be associated with the specified key.

Returns: the previous value associated with the specified key, or null if there was no mapping for the key.

Throws:

1. UnsupportedOperationException - if the put operation is not supported by this map.

2. ClassCastException - if the class of the specified key or value prevents it from being stored in this map.

3. NullPointerException - if the specified key or value is null, and this map does not permit null keys or values.

4. IllegalArgumentException - if some property of the specified key or value prevents it from being stored in this map.

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapreplace {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        String key = "Java";
        Integer value = 3;

        System.out.println(weakHashMap.replace(key, value));

    }
}

Output:

1


WeakHashMap remove(Object, Object) in Java

remove(Object, Object): This method is available in java.util.WeakHashMap class of Java.

Syntax:

boolean java.util.Map.remove(Object key, Object value)

This method takes two arguments. This method removes the entry for the specified key only if it is currently mapped to the specified value.

Parameters: Two parameters are required for this method.

key: key with which the specified value is associated.

value: value expected to be associated with the specified key.

Returns: true if the value was removed.

Throws:

1. UnsupportedOperationException - if the remove operation is not supported by this map.

2. ClassCastException - if the key or value is of an inappropriate type for this map.

3. NullPointerException - if the specified key or value is null, and this map does not permit null keys or values.

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapremove2 {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        Object key = "Java", value = 2;

        System.out.println(weakHashMap.remove(key, value));

    }
}

Output:

false


WeakHashMap remove(Object) in Java

remove(Object): This method is available in java.util.WeakHashMap class of Java.

Syntax:

V java.util.WeakHashMap.remove(Object key)

This method takes one argument. This method removes the mapping for a key from this weak hash map if it is present.

Parameters: One parameter is required for this method.

key: key whose mapping is to be removed from the map.

Returns: the previous value associated with key, or null if there was no mapping for key.

Exceptions: NA

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapremove {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        Object key = "Java";

        System.out.println(weakHashMap.remove(key));

    }
}

Output:

1


WeakHashMap putIfAbsent(K, V) in Java

putIfAbsent(K, V): This method is available in java.util.WeakHashMap  class of Java.

Syntax:

V java.util.Map.putIfAbsent(K key, V value)

This method takes two arguments. If the specified key is not already associated with a value associated with the given value and returns null, else returns the current value.

Parameters: Two parameters are required for this method.

key: key with which the specified value is to be associated.

value: value to be associated with the specified key.

Returns: the previous value associated with the specified key, or null if there was no mapping for the key.

Throws:

1. UnsupportedOperationException - if the put operation is not supported by this map.

2. ClassCastException - if the key or value is of an inappropriate type for this map.

3. NullPointerException - if the specified key or value is null, and this map does not permit null keys or values.

4. IllegalArgumentException - if some property of the specified key or value prevents it from being stored in this map.

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapputIfAbsent {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        String key = "C++";
        Integer value = 3;

        System.out.println(weakHashMap.putIfAbsent(key, value));

    }
}

Output:

null


WeakHashMap putAll(Map) in Java

putAll(Map): This method is available in java.util.WeakHashMap class of Java.

Syntax:

void java.util.WeakHashMap.putAll(Map<? extends K, ? extends V> m)

This method takes one argument. This method copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.

Parameters: One parameter is required for this method.

m: mappings to be stored in this map.

Throws:

NullPointerException - if the specified map is null.

Approach 1: When no exception

Java

import java.util.WeakHashMap;

public class WeakHashMapputAll {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        WeakHashMap<String, Integer> m =
new WeakHashMap<String, Integer>();

        m.put("Python", 3);
        m.put("C++", 4);

        weakHashMap.putAll(m);

        System.out.println(weakHashMap);

    }
}

Output:

{Hello=2, Java=1, C++=4, Python=3}


Approach 2: NullPointerException

Java

import java.util.WeakHashMap;

public class WeakHashMapputAll {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        WeakHashMap<String, Integer> m = null;

        weakHashMap.putAll(m);

        System.out.println(weakHashMap);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Map.size()" because "m" is null at java.base/java.util.WeakHashMap.putAll(WeakHashMap.java:542)


WeakHashMap put(K, V) in Java

put(K, V): This method is available in java.util.WeakHashMap class of Java.

Syntax:

V java.util.WeakHashMap.put(K key, V value)

This method takes two arguments. This method associates the specified value with the specified key in this map.

Note: The old value is replaced if the map previously contained a mapping for this key.

Parameters: Two parameters are required for this method.

key: key with which the specified value is to be associated.

value: value to be associated with the specified key.

Returns: the previous value associated with key, or null if there was no mapping for key.

Exceptions: NA

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapput {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 2);
        weakHashMap.put("Hello", 1);

        System.out.println(weakHashMap);

    }
}

Output:

{Hello=1, Java=2}


WeakHashMap merge(K, V, BiFunction) in Java

merge(K, V, BiFunction): This method is available in java.util.WeakHashMap class of Java.

Syntax:

V java.util.Map.merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

This method takes three arguments. If the specified key is not already associated with a value or is associated with null, associate it with the given non-null value.

Parameters: Three parameters are required for this method.

key: key with which the resulting value is to be associated.

value: the non-null value to be merged with the existing value associated with the key or if no existing value or a null value is associated with the key, to be associated with the key.

remappingFunction: the remapping function to recompute a value if present.

Returns: the new value associated with the specified key, or null if no value is associated with the key.

Throws:

1. UnsupportedOperationException - if the put operation is not supported by this map.

2. ClassCastException - if the class of the specified key or value prevents it from being stored in this map.

3. IllegalArgumentException - if some property of the specified key or value prevents it from being stored in this map.

4. NullPointerException - if the specified key is null and this map does not support null keys or the value or remappingFunction is null.

Approach 1: When no exception

Java

import java.util.WeakHashMap;
import java.util.function.BiFunction;

public class WeakHashMapmerge {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        String key = "Java";
        Integer value = 1;

        BiFunction<? super Integer, ? super
Integer, ? extends Integer> remappingFunction =
(k, v) -> k + v;

        System.out.println(weakHashMap.merge(key,
value, remappingFunction));

    }
}

Output:

2


Approach 2: NullPointerException 

Java

import java.util.WeakHashMap;
import java.util.function.BiFunction;

public class WeakHashMapmerge {
    public static void main(String[] args) {

        WeakHashMap<String, Integer> weakHashMap =
new WeakHashMap<String, Integer>();

        weakHashMap.put("Java", 1);
        weakHashMap.put("Hello", 2);

        String key = "Java";
        Integer value = 1;

        BiFunction<? super Integer, ? super Integer,
? extends Integer> remappingFunction = null;
        System.out.println(weakHashMap.merge(key,
value, remappingFunction));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Map.merge(Map.java:1265)


WeakHashMap keySet() in Java

keySet(): This method is available in java.util.WeakHashMap class of Java.

Syntax:

Set<K> java.util.WeakHashMap.keySet()

This method returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Parameters: NA

Returns: a set view of the keys contained in this map.

Exceptions: NA

Approach

Java

import java.util.WeakHashMap;

public class WeakHashMapkeySet {
    public static void main(String[] args) {

        WeakHashMap<String, String> weakHashMap =
new WeakHashMap<String, String>();

        weakHashMap.put("Java", "Program");
        weakHashMap.put("Hello", "World");

        System.out.println(weakHashMap.keySet());

    }
}

Output:

[Hello, Java]