Replace Elements

  1. replace(key, value) - replaces the value associated with the specified key by a new value.
  2. replace(key, old, new) - replaces the old value with the new value only if old value is already associated with the specified key.
  3. replaceAll(function) - replaces each value of the map with the result of the specified function.


\begin{lstlisting}
import java.util.HashMap ;
\par
class Main {
public static v...
...m.out.println(''HashMap using replaceAll ():'' + numbers);
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Original HashMap : { Second =2 , Third =3 , First =1}
HashMap...
...HashMap using replaceAll : { Second =24 , Third =35 , First =3}
\end{lstlisting}

In the above program notice the statement numbers.replaceAll((key, oldValue) -> oldValue + 2);. This method accesses all the entries of the map. It then replaces all the values with the new values provided by the lambda expression. There isn’t any description about lambda expression in this book, for the scope is beyond the aims of this text.