Example 1: Update value of HashMap using put()
Output
HashMap: {Second=2, Third=3, First=1}
HashMap with updated value: {Second=4, Third=3, First=1}
In the above example, we have used the HashMap put() method to update the value of the key Second. Here, first, we access the value using theĀ HashMap get() method.
Example 2: Update value of HashMap using computeIfPresent()
Output
HashMap: {Second=2, First=1}
HashMap with updated value: {Second=4, First=1}
In the above example, we have recomputed the value of the key Second using the computeIfPresent() method. To learn more, visit HashMap computeIfPresent().
Here, we have used the lambda expression as the method argument to the method.
Example 3: Update value of Hashmap using merge()
Output
HashMap: {Second=2, First=1}
HashMap with updated value: {Second=2, First=5}
In the above example, the merge() method adds the old value and new value of the key First. And, insert the updated value to HashMap. To learn more, visit HashMap merge().