In this Java Tutorial we will go over details on how to use HashMap’s below methods:
clone()
putIfAbsent(K key, V value)
computeIfAbsent(K key, java.util.function.Function mappingFunction)
computeIfPresent(K key, java.util.function.BiFunction remappingFunction)
hashMap.clone():
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
hashMap.putIfAbsent():
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
hashMap.computeIfAbsent():
If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
hashMap.computeIfPresent():
If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
Let’s get started:
Create Java class CrunchifyCloneHashmap.java
Put below code into it
In above Java code, you wont see crunchifyHashMapNew.putIfAbsent(“Crunchify”, 16); added to new HashMap.
Just run above program as a Java Application in either in Eclipse IDE or IntelliJ IDEA.
You should see console result similar to this:
Let me know if you face any issue running code.
The post HashMap’s clone(), putIfAbsent(), computeIfAbsent(), computeIfPresent() Methods in Java (Examples) appeared first on Crunchify.
More Related Articles For You...
In Java What is a Difference Between IdentityHashMap and HashMap + Performance Comparison
How to Sort a HashMap by Key and Value in Java 8 – Complete Tutorial
Ansible: How to terminate all AWS EC2 instances using Ansible script?