Using merge() Method

The merge() method associates the specified value to the specified key if the specified key is not already associated. However, if the specified key is already associated with a value, it will merge the new specified value with the existing old value. For example,


\begin{lstlisting}
import java.util.HashMap;
\par
class Main {
public static vo...
...Value);
System.out.println(''New HashMap : '' + numbers);
}
}
\end{lstlisting}

Output


\begin{lstlisting}
1 Original HashMap : { Second =2 , First =1}
2 New HashMap : { Second =2 , First =5}
\end{lstlisting}

Other methods of HashMap.


Table 2.6:
Method Description
clear() Removes all the entries from the map
containsKey() Checks if the map contains the specified
key and returns a boolean value
containsValue() Checks if the map contains the specified
value and returns a boolean value
size() Returns the size of the map
isEmpty() Checks if the map is empty and returns
a boolean value


In the above example, the merge() method takes 3 parameters: key, newValue and a lambda expression (that computes the new merged value).