In the Map collection framework, in addition to HashMap, TreeMap is also one of the collection objects commonly used in work.
Compared with HashMap, TreeMap is a Map collection that can compare elements, and sorts the key value. For comparasion, you can use the natural order of the elements, or you can use a custom comparator in the collection to sort;
Unlike HashMap‘s hash mapping, the underlying structure of the TreeMap is a tree structure. As for the specific form, you can simply understand it as an inverted tree — roots up, leaves down. In computer terms, TreeMap implements the structure of a red-black tree, forming a binary tree.
TreeMap inherits AbstractMap and implements Map, Cloneable, NavigableMap, and Serializable interfaces.
TreeMap inherits AbstractMap, and AbstractMap implements the Map interface and implements the methods defined in the Map interface, reducing the complexity of subclass inheritance;
TreeMap implements the Map interface and becomes a member of the Map framework, which can store elements in the form of key-value;
TreeMap implements the NavigableMap interface, which means that it has stronger element searching capabilities;
TreeMap implements the Cloneable interface and implements the clone() method, so it can be cloned;
TreeMap implements the Java.io.Serializable interface, supports serialization operations, and can be transmitted through the Hessian protocol;
For Cloneable, Serializable, we are familiar with it. Basically, every class in the Java collection framework will implement these 2 interfaces. But what does the NavigableMap interface do and what functions does it define? Next, let’s take a look at the source code of NavigableMap!
Let’s first introduce the SortedMap interface in the NavigableMap system:
For SortedMap, this class is the parent interface in the TreeMap, and it is also the most critical interface different from the HashMap system.
The main reason is the first method defined in the SortedMap interface: Comparator<?Super K> comparator();
With the comparator, the inserted elements can be sorted.
publicinterfaceSortedMap<K,V> extendsMap<K,V> { //Returns the element comparator. If the order is natural, return null; Comparator<? super K> comparator(); //Returns the collection from `fromKey` to `toKey`: with head but no tail java.util.SortedMap<K,V> subMap(K fromKey, K toKey);
//Returns the collection from head to `toKey`: without 'toKey' java.util.SortedMap<K,V> headMap(K toKey);
//Returns the collection from `fromKey` to tail: with 'fromKey' java.util.SortedMap<K,V> tailMap(K fromKey); //Returns the first element in the collection K firstKey(); //Returns the last element in the collection K lastKey(); //Returns all keys in the collection Set<K> keySet(); //Returns all values in the collection: Collection<V> values(); //Returns key-value map of elements Set<Map.Entry<K, V>> entrySet(); }
The NavigableMap interface is a further extension of SortedMap: it mainly adds search and retrieval operations for elements in the collection, such as returning elements in a range in the collection, returning elements less than a certain value, and so on.
In fact, the purpose of NavigableMap is very simple and straightforward, which is to enhance the search and retrieval functions for the elements in the collection. When the subclass TreeMap is implemented, the above functions are naturally obtained;
TreeMap has the following characteristics:
Duplicate keys are not allowed;
Can insert null key, null value;
Can sort elements;
Unordered collection (insertion and traversal order are inconsistent);
//get elements //get element whose key is "developer" Integer getValue = treeMap.get("developer"); //get first key String firstKey = treeMap.firstKey(); //get last key String lastKey =treeMap.lastKey(); //get first element whose key is less than "developer" String lowerKey =treeMap.lowerKey("developer"); //get first element whose key is greater than "developer" String ceilingKey =treeMap.ceilingKey("developer"); //get collections whose key is from "i"到"a"的元素 SortedMap<String,Integer> sortedMap =treeMap.subMap("i","a");
//delete elemetns //delete element whose key is "developer" Integer removeValue = treeMap.remove("developer"); // clear collection treeMap.clear();
// if collection is empty boolean isEmpty = treeMap.isEmpty(); //if collection contains element whose key is "developer" boolean isContain = treeMap.containsKey("developer"); } }
TreeMap sorting
In the previous section, the code showed the simple use of TreeMap. In the first section, I mentioned that TreeMap is a collection that can sort elements. So how to sort it?
Use natural order of elements
When using natural order sorting, there are two cases: one is the object defined by Jdk, and the other is the object we define.
In the natural order comparison, the elements being compared need to implement the Comparable interface, otherwise when adding an element to the collection will have “java.lang.ClassCastException: com.jiaboyan.collection.map.SortedObject cannot be cast to java.lang.Comparable “ exception;
This is because when the put() method is called, the element will be converted into a Comparable type object, so when the element passed in does not implement the Comparable interface, it cannot be converted and an exception will be reported;
Use custom comparator
To use a custom comparator for sorting, you need to pass the custom comparator object to the TreeMap constructor when you create the TreeMap object;
A custom comparator object needs to implement the Comparator interface and implement the compare method compare(T o1, T o2);
It is worth noting that if you use a custom comparator to sort, the compared objects no longer need to implement the Comparable interface;