What is the TreeMap class in Java?
Introduction
The TreeMap class belongs to java.util.package. The TreeMap is stored in the form of keys and values format, but it maintains ascending and sorting order by using their keys.
Syntax
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable
Parameters
K: This is the type of key maintained in the TreeMap
V: This is the type of value maintained in the TreeMap
Example
import java.util.TreeMap;class Main {public static void main(String[] args) {// Creating TreeMap of empIDTreeMap<String, Integer> empID = new TreeMap<>();// Using put()empID.put("John", 3);empID.put("Charlie",4);empID.put("Jack",5);System.out.println("TreeMap of empID:"+empID);}}
Explanation
- First, import the
TreeMapfrom theutil, and introduce the main class. - Create an object with arguments of string and integer of
empID. - Using the put method enter the keys(as string) and values(as integer).
- Now print
empID. - It will return the natural sorting order of
empIDusing their keys. - Likewise, you can use the many methods of
TreeMap. For example,removemethod to remove the element.
Some methods supported by TreeMap
Method Name | Syntax | Usage |
clear | Tree_Map.clear() | The |
containsKey | Tree_Map.containsKey(key_element) | The |
containsValue | Tree_Map.containsValue(Object Value) | The |
get | Tree_Map.get(Object key_element) | The |
keySet | Tree_Map.keySet() | The |
put | Tree_Map.put(key, value) | The |
remove | Tree_Map.remove(Object key) | The |
size | Tree_Map.size(key) | The |
values | Tree_Map.values() | The |