The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
- It is the implementation class of Map interface.
- It sorts the element on the basis of keys.
- It does not maintain insertion order.
Ways by which we can replace the value using the given key:
- Using put() method of TreeMap class
- Using replace() method of TreeMap class
- Using ComputeIfPresent() method of TreeMap class
1. put() method:
Parameters: The method takes two parameters, both are of the Object type of the TreeMap.
- key: This refers to the key element that needs to be inserted into the Map for mapping.
- value: This refers to the value that the above key would map into.
Return Value: If an existing key is passed then the previous value gets returned. If a new pair is passed, then NULL is returned.
- Using put method we can replace the value of the key that is already present but if the key is not present it creates a new record.
dsa , 99 fang , 99 interview , 98
2. Using replace() method :
- replace() method replaces the value of the given key but there is difference between replace and put.
- In case of replace if the key is not present it does not create a new record.
public V replace(K key, V value)
Parameters: This method accepts two parameters:
- key: which is the key of the element whose value has to be replaced.
- value: which is the new value which has to be mapped with the provided key.
Return Value: This method returns the previous value associated with the specified key. If there is no such key mapped, then it returns null, if the implementation supports null value.
Exceptions: This method will throw:
- NullPointerException if the specified key or value is null, and this map does not permit null keys or values and
- IllegalArgumentException if some property of the specified key or value prevents it from being stored in this map.
dsa , 100 fang , 80 interview , 98
3. computeIfPresent() method:
- It is present in java 8. The computeIfPresent(Key, BiFunction) method of HashMap class which allows you to compute value of mapping for a specified key if key is already associated with a value (or is mapped to null).
dsa , 99 fang , 80 interview , 50
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.