TreeMap overview
TreeMap class implements Map interface and its built using tree based data structure
Main features of TreeMap
TreeMap is similar to any other Map which stores key-value pair
Elements in TreeMap will be in sorted order based on keys sorting
It contains only unique keys
It does not allow NULL key but NULL values are allowed
TreeMap can be created using constructor as below
- TreeMap tm = new TreeMap();
TreeMap tm = new TreeMap();
Important methods in TreeMap
put(Object key, Object value)
This method stores the specified value and associates it with the specified key in this map.
get(Object key)
This method will return the value associated with a specified key in this map.
firstEntry()
Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
firstKey()
Returns the first (lowest) key currently in this map.
lastKey()
Returns the last (highest) key currently in this map
size()
Returns the number of key-value mappings in this map.
Example
- import java.util.*;
- public class TreeMapExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(5, "Five");
- tm.put(3, "Three");
- tm.put(2, "Two");
- tm.put(4, "Four");
- tm.put(1, "One");
- System.out.println(“TreeMap is …”);
- System.out.println(tm);
- System.out.println("Value for the key 1 is "+tm.get(1));
- System.out.println("Value for the key 10 is "+tm.get(10));
- System.out.println("First key in the map is "+tm.firstKey());
- System.out.println("Last key in the map is "+tm.lastKey());
- System.out.println("Number of elements in map is "+tm.size());
- }
- }
import java.util.*; public class TreeMapExample { public static void main(String args[]) { TreeMap<Integer,String> tm = new TreeMap<>(); tm.put(5, "Five"); tm.put(3, "Three"); tm.put(2, "Two"); tm.put(4, "Four"); tm.put(1, "One"); System.out.println(“TreeMap is …”); System.out.println(tm); System.out.println("Value for the key 1 is "+tm.get(1)); System.out.println("Value for the key 10 is "+tm.get(10)); System.out.println("First key in the map is "+tm.firstKey()); System.out.println("Last key in the map is "+tm.lastKey()); System.out.println("Number of elements in map is "+tm.size()); } }
When to use TreeMap ?
Whenever we want to store data in key-value pair format and whenever we need to have elements in the sorted order
When not to use TreeMap ?
Whenever we don’t want to store key-value pair data and Whenever we don’t want to store elements in sorted order