HashMap: Java 8 Improvements
Let's discuss the improvements made in the HashMap class in Java 8.
We'll cover the following
In this lesson, we will look at some of the HashMap operations that were added with Java 8.
The compute()
method
The compute(Key, BiFunction)
method allows us to update a value in HashMap. This method tries to compute a mapping for the specified key and its current mapped value (or null if no current mapping is found). This method is used to atomically update a value for a given key in HashMap.
- If the remapping function passed in compute returns
null
, the mapping is removed from the Map (or remains absent if initially absent). - If the remapping function throws an exception, the exception is rethrown, and the current mapping is left unchanged.
The syntax of this method is:
compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
Let’s say we have a HashMap in which the key is a String, and the value is an Integer. We need to increment the value for a given key by one, and if the key is not present, we need to insert the key with the default value of 10. We can create a lambda expression and pass it to the compute()
method.
Get hands-on with 1400+ tech skills courses.