Replacing values in a Map

Java 11 Certification Practice Questions (For the complete list, refer http://talks.skilltoz.com/java-11-certification-exam-questions/)

How do we replace a value in a Map?

The replace‚Äč(K key, V value) of Map replaces the entry for the specified key with the specified value only if it is currently mapped to some value. It returns the value that was associated with this key earlier.

Let us see an example below.

Map<Integer, Integer> map = new HashMap<>();
map.put(1, 12);
map.put(12, 4);
Integer prev = map.replace(12, 10); 
System.out.println(prev); // prints 4
System.out.println(map);  // prints {1=12, 12=10}

In this example, the replace() method is called to replace the value of the key 12 with a new value 10. After replacing, the previous value of the key is returned, hence 4 is printed. The contents of the map will be {1=12, 12=10}.

What will happen if the replace() method is called with a key that does not exist in the map?

The replace() method does nothing if it is called with a key that does not exist in the map. No error occurs. The value returned will be null.

How does the replace() method differ from the put() method?

If a value is already mapped to the given key, both put and replace will update the map in the same way. Both methods will also return the previous value associated with the key. However, if there is no mapping for the key, then replace will do nothing, whereas put will update the map.

How does replaceAll() work?

The replaceAll() method replaces the value of each entry in the map with the result of calling the function specified in the parameter. Let us see an example.

Map<Integer, Integer> map = new HashMap<>();
map.put(1, 12);
map.put(12, 4);
map.replaceAll((k, v) -> k + v);
System.out.println(map);	// prints {1=13, 12=16}

In the above code, the function passed to the replaceAll() method returns the sum of key and value for every entry in the map. This will replace the value of each entry. Thus the value of the entry with key 1 becomes 13 and the value of the entry with key 12 becomes 16.

Quiz

Q1. What will be the result?
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 12);
map.put(12, 4);
map.replace(12, null); 
map.replace(11, 1); 
System.out.println(map);

Quiz Answer

For answers to the above question and other questions on Map, visit https://thinkassess.com/java/maps-in-java-quiz/

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *