TreeMap in Java with Examples
TreMap is a Map, a set of key-value pairs.It is a Red-Black tree based NavigableMap implementation.
It is a member of the java collection framework.
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.
Important points about TreeMap
The TreeMap implementation provides guaranteed log(n) time cost for the containsKey, get, put, and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.
The ordering in the TreeMap is maintained by a treemap, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface.
TreeMap is not synchronized.
If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
To use the Synchronized version of TreeMap we have to use Collections.synchronizedSortedMap method.
This is best done at creation time, to prevent accidental unsynchronized access to the map:
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));The iterators returned by the iterator method of TreeMap are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.
TreeMap entries are sorted in the natural ordering of its keys. It also provides a constructor to provide Comparator to be used for ordering. So if you are using any class as key, make sure it’s implementing Comparable interface for natural ordering.
All Map.Entry pairs returned by methods in TreeMap do not support the Entry.setValue method.
TreeMap in java doesn’t allow null keys, however, you can have multiple null values associated with different keys.
The following is the simple example of TreeMap which stores key Value pairs according to Natural Sorting order.
import java.util.SortedMap;
import java.util.TreeMap;
public class CreateTreeMapExample {
public static void main(String[] args) {
// Creating a TreeMap
SortedMap < String,
String > currencyMap = new TreeMap <>();
currencyMap.put("India", "Indian rupee");
currencyMap.put("United States of America", "United States dollar");
currencyMap.put("Afghanistan", "Afghan afghani");
currencyMap.put("Australia", "Australian dollar");
currencyMap.put("Vietnam", "Vietnamese dong");
currencyMap.put("Yemen", "Yemeni rial");
currencyMap.put("Zimbabwe", "United States dollar");
currencyMap.put("Thailand", "Thai baht");
currencyMap.put("South Korea", "South Korean won");
currencyMap.put("Singapore", "Singapore dollar");
currencyMap.put("Romania", "Romanian leu");
currencyMap.put("Poland", "Polish zloty");
// Printing the TreeMap (Output will be sorted based on keys)
System.out.println(currencyMap);
}
}
output:
{Afghanistan=Afghan afghani, Australia=Australian dollar, India=Indian rupee, Poland=Polish zloty, Romania=Romanian leu, Singapore=Singapore dollar, South Korea=South Korean won, Thailand=Thai baht, United States of America=United States dollar, Vietnam=Vietnamese dong, Yemen=Yemeni rial, Zimbabwe=United States dollar}
TreeMap vs HashMap
S.N | TreeMap | HashMap |
---|---|---|
1. | TreeMap uses a Red-Black tree based NavigableMap implementation. | HashMap uses hashing algorithm implementation. |
2 | TreeMap entries are sorted in natural ordering of keys | HashMap doesn’t store entries in any order. |
3 | TreeMap doesn’t allow null key. | we can have one null key in HashMap |
4 | Since TreeMap stores entries in a sorted way, it’s a bit slower than HashMap in storing and retrieving objects. | HashMap is faster than TreeMap. |
Constructor Details
There are a total of 4 Constructors in TreeMap class.
1). public TreeMap()
Constructs a new, empty treemap, using the natural ordering of its keys.
All keys inserted into the map must implement the Comparable interface. Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map.
If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), the put(Object key, Object value) call will throw a ClassCastException.
2). public TreeMap(Comparator comparator)
Constructs a new, empty treemap, ordered according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator: comparator.compare(k1, k2) must not throw a ClassCastException for any keys k1 and k2 in the map.
If the user attempts to put a key into the map that violates this constraint, the put(Object key, Object value) call will throw a ClassCastException.
Parameters:
comparator - the comparator that will be used to order this map. If null, the natural ordering of the keys will be used.
3). public TreeMap(Map m)
Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.
All keys inserted into the new map must implement the Comparable interface. Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map.
This method runs in n*log(n) time. Parameters: m - the map whose mappings are to be placed in this map Throws: ClassCastException - if the keys in m are not Comparable, or are not mutually comparable NullPointerException - if the specified map is null.
4). public TreeMap(SortedMap m)
Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method runs in linear time. Parameters: m - the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map Throws: NullPointerException - if the specified map is null.
TreeMap Methods1). public int size()
Returns the number of key-value mappings in this map.
2). containsKey
public boolean containsKey(Object key) It will throws
ClassCastException - if the specified key cannot be compared with the keys currently in the map.
NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.
3).containsValue
public boolean containsValue(Object value)Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations.
4). get
public V get(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. More formally, if this map contains a mapping from a key k to a value v such that key compares equal to k according to the map's ordering, then this method returns v; otherwise, it returns null. (There can be at most one such mapping.)
A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.
It will throws
ClassCastException - if the specified key cannot be compared with the keys currently in the map.
NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.
5). comparator
Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
6). firstKey
Returns the first (lowest) key currently in this map. It will NoSuchElementException - if this map is empty.
7). lastKey
public K lastKey()Returns the last (highest) key currently in this map. It will NoSuchElementException - if this map is empty.
8). putAll
putAll(Map map)Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map.
It will throws
ClassCastException - if the specified key cannot be compared with the keys currently in the map.
NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.
9). put
public V put(K key,V value)Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
It will throws
ClassCastException - if the specified key cannot be compared with the keys currently in the map.
NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.
10). remove
public V remove(Object key)Removes the mapping for this key from this TreeMap if present.
It will throws
ClassCastException - if the specified key cannot be compared with the keys currently in the map.
NullPointerException - - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.
TreeMap with a custom Comparator with Descending Order
import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapWithComparator {
public static void main(String[] args) {
SortedMap < String,
String > currencyMap = new TreeMap < >(new Comparator < String > () {@Override
public int compare(String s1, String s2) {
return s2.compareTo(s1);
}
});
currencyMap.put("India", "Indian rupee");
currencyMap.put("United States of America", "United States dollar");
currencyMap.put("Afghanistan ", "Afghan afghani");
currencyMap.put("Australia", "Australian dollar");
currencyMap.put("Vietnam", "Vietnamese dong");
currencyMap.put("Yemen", "Yemeni rial");
currencyMap.put("Zimbabwe", "United States dollar");
currencyMap.put("Thailand", "Thai baht");
currencyMap.put("South Korea", "South Korean won");
currencyMap.put("Singapore", "Singapore dollar");
currencyMap.put("Romania", "Romanian leu");
currencyMap.put("Poland", "Polish zloty");
// Printing the TreeMap (Output will be sorted based on keys)
System.out.println(currencyMap);
}
}
output:
{Zimbabwe=United States dollar, Yemen=Yemeni rial, Vietnam=Vietnamese dong, United States of America=United States dollar, Thailand=Thai baht, South Korea=South Korean won, Singapore=Singapore dollar, Romania=Romanian leu, Poland=Polish zloty, India=Indian rupee, Australia=Australian dollar, Afghanistan =Afghan afghani}
Post/Questions related to TreeMap in Java with Examples
How to check special characters in java using Regex?
In this article, we have seen TreeMap in Java with Examples. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment