Java TreeMap tutorial with examples will help you understand how to use the Java TreeMap class in an easy way. TreeMap in Java is a tree based implementation of the Map interface. The TreeMap class implements the NavigableMap interface. Unlike the HashMap class, the keys of the TreeMap are sorted according to the natural ordering or by the custom comparator.
If you do not want the keys to be sorted by their natural ordering but by custom order, you can do so by providing the custom Comparator at the time of TreeMap creation using the below given constructor.
1 |
public TreeMap(Comparator comparator) |
The TreeMap in Java provides log(n)
time cost for get
, put
, remove
and containsKey
operations.
The TreeMap implementation is not synchronized. If multiple threads are trying to modify the TreeMap object simultaneously, then the access must be synchronized explicitly. You can either synchronize the TreeMap object or you can get the synchronized SortedMap object from the existing TreeMap using the synchronizedSortedMap
method of the Collections class as given below.
1 |
SortedMap sortedMap = Collections.synchronizedSortedMap(existingTreeMapObject); |
The Iterator object obtained by the iterator
method of the TreeMap is fail-fast. That means if the TreeMap object is structurally modified after obtaining the iterator (except by using iterator’s own remove
method), calling any methods of the iterator object will throw ConcurrentModificationException
.
How to create TreeMap objects?
The TreeMap class in Java provides several constructors to create the objects. The default constructor of the TreeMap class creates a new empty TreeMap object. The key-value pairs stored in this TreeMap object are stored by the natural ordering of its keys.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* * This will create a new empty TreeMap */ TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); /* * mappings will be sorted by the * natural ordering of the keys */ tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); //this will print sorted TreeMap key-value pairs System.out.println( tMap ); |
Output
1 |
{1=One, 2=Two, 3=Three} |
As you can see from the output, the treemap entries are sorted by keys using the natural ordering.
If you want to specify the custom order, use the overloaded constructor having the Comparator argument.
1 |
public TreeMap(Comparator<? super K> comparator) |
The objects in this TreeMap will be sorted by the keys in the order defined by the provided custom comparator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/* * This comparator will sort the Integer * objects in the descending order */ class ExampleComparator implements Comparator<Integer>{ //descending order public int compare(Integer i1, Integer i2) { return i2 - i1; } } public class Example { public static void main(String[] args) { /* * This will create a new empty TreeMap * with custom comparator */ TreeMap<Integer, String> tMap = new TreeMap<Integer, String>( new ExampleComparator() ); /* * mappings will be sorted by * the keys using the provided comparator */ tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println( tMap ); } } |
Output
1 |
{3=Three, 2=Two, 1=One} |
As you can see from the output, the mappings are now sorted in descending order by the custom comparator we provided in the TreeMap constructor.
The TreeMap class in Java also provides an overloaded constructor that accepts the Map argument. Using this constructor you can convert HashMap to TreeMap.
1 |
public TreeMap(Map<? extends K, ? extends V> map) |
This constructor creates a new TreeMap having the same key value pairs as the given map object ordered by the natural ordering of the keys. Important: All the keys inserted in the TreeMap must implement the Comparable interface.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//new HashMap object HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(3, "Three"); map.put(1, "One"); map.put(2, "Two"); /* * Create a new TreeMap from HashMap * using the constructor * i.e. convert HashMap to TreeMap */ TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(map); //the entries in the TreeMap are sorted by keys System.out.println("TreeMap contains: " + tMap); |
Output
1 |
TreeMap contains: {1=One, 2=Two, 3=Three} |
How to add objects to TreeMap using the put, putAll, and putIfAbsent methods?
The TreeMap put
method adds given key and value to the treemap object. If the TreeMap already contains the key, the value associated with the key will be replaced by the new value. In this case, the previous value will be returned. It returns null if there was no value associated with the key previously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); /* * Use put method to add key-value pairs */ tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println( tMap ); /* * If the key already exists, the * old value will be replaced by the new value */ tMap.put(2, "NewTwo"); System.out.println( tMap ); |
Output
1 2 |
{1=One, 2=Two} {1=One, 2=NewTwo} |
Similarly, the putAll
method of the TreeMap class copies all the mappings contained in the given map object to this treemap object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(1, "One"); tMap.put(5, "Five"); HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(3, "Three"); map.put(2, "Two"); map.put(4, "Four"); /* * Use putAll method to copy all the * mappings from HashMap to TreeMap */ tMap.putAll(map); //pairs will be sorted automatically System.out.println( tMap ); |
Output
1 |
{1=One, 2=Two, 3=Three, 4=Four, 5=Five} |
As you can see from the output, the key-value pairs copied from the HashMap will be automatically inserted into the TreeMap object in sorted order.
The putIfAbsent
method of the TreeMap class adds a key-value mapping to the TreeMap object if the key is not currently associated with any value and returns null. If the specified key already exists in the TreeMap, the putIfAbsent
method does nothing and returns the value associated with the specified key.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); /* * This will add 7=>Seven mapping to the * TreeMap object as key 7 does not exist * and returns null */ System.out.println( tMapOddNumbers.putIfAbsent(7, "Seven") ); System.out.println("TreeMap contains: " + tMapOddNumbers); /* * This will not add the mapping as the key * 5 already exists, and returns the value * currently associated with the key 5 i.e. "Five" */ System.out.println( tMapOddNumbers.putIfAbsent(5, "NewFive") ); System.out.println("TreeMap contains: " + tMapOddNumbers); |
Output
1 2 3 4 |
null TreeMap contains: {1=One, 3=Three, 5=Five, 7=Seven} Five TreeMap contains: {1=One, 3=Three, 5=Five, 7=Seven} |
Difference between put and putIfAbsent methods: If the specified key is already mapped to some value in the TreeMap, the put
method replaces the value currently associated with the specified key with the new value, while the putIfAbsent
method does not do anything.
How to get objects from TreeMap?
1. How to get the value mapped to a key from the TreeMap using get method?
The get
method of the TreeMap class returns a value associated with the given key. If the key does not exist in the TreeMap, it returns null.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(1, "One"); tMap.put(5, "Five"); /* * Use get method to get the value * associated with the key */ //this will print "One" System.out.println( tMap.get(1) ); //this will print null as key does not exists System.out.println( tMap.get(2) ); |
Output
1 2 |
One null |
2. How to get a default value for a key if the key does not exist in the TreeMap?
The getOrDefault
method returns the value associated with the specified key if the key is mapped to some value in the TreeMap. If the mapping does not exist for the key, it returns the specified default value instead of null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); /* * This will return "Three" as the key * 3 is mapped to value "Three" */ System.out.println( tMapOddNumbers.getOrDefault(3, "000") ); /* * This will return "000" as the key * 4 is not mapped to any value in the TreeMap */ System.out.println( tMapOddNumbers.getOrDefault(4, "000") ); |
Output
1 2 |
Three 000 |
3. How to get the first key, first value, or first entry from the TreeMap?
The TreeMap class in Java provides the firstEntry
and firstKey
methods to get the first entry and first key stored in the treemap object respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); /* * Use the firstKey method of the TreeMap * to get the first key */ System.out.println("First key: " + tMap.firstKey()); /* * Use the get method along with the firstKey method * to get the first value */ System.out.println("First value: " + tMap.get( tMap.firstKey() )); /* * You can also use the firstEntry method * to get the first key-value pair from the TreeMap */ Map.Entry<Integer, String> entry = tMap.firstEntry(); System.out.println("First entry: " + entry.getKey() + "=>" + entry.getValue()); |
Output
1 2 3 |
First key: 1 First value: One First entry: 1=>One |
4. How to get the last key, last value, or last entry from the TreeMap?
The lastEntry
and lastKey
methods of the TreeMap class return the last entry and last key stored in the treemap object respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); /* * Use the lastKey method of the TreeMap class * to get the last key */ System.out.println("Last key: " + tMap.lastKey()); /* * Use the get method along with the lastKey method * to get the last value */ System.out.println("Last value: " + tMap.get( tMap.lastKey() )); /* * You can also use the lastEntry method * to get the last key-value pair from the TreeMap */ Map.Entry<Integer, String> entry = tMap.lastEntry(); System.out.println("Last entry: " + entry.getKey() + "=>" + entry.getValue()); |
Output
1 2 3 |
Last key: 3 Last value: Three Last entry: 3=>Three |
5. How to get the key greater than the specified key from the TreeMap?
Using the higherKey and higherEntry methods:
The higherKey
method returns a key greater than the specified key from the TreeMap. Similarly, the higherEntry
method returns an entry from the TreeMap having a key greater than the specified key.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); /* * This will get the key greater than the * specified key from the TreeMap. */ System.out.println( tMapOddNumbers.higherKey(3) ); /* * This will get the entry having a key * which is greater than the specified key */ System.out.println( tMapOddNumbers.higherEntry(3) ); /* * Both of these methods return null, if there is * no greater key in the TreeMap */ System.out.println( tMapOddNumbers.higherKey(9) ); System.out.println( tMapOddNumbers.higherEntry(9) ); |
Output
1 2 3 4 |
5 5=Five null null |
Using the ceilingKey and ceilingEntry methods:
The ceilingKey
method returns the smallest key from the TreeMap that is greater than or equal to the specified key. Similarly, the ceilingEntry
method returns an entry having the smallest key that is greater than or equal to the specified key.
Both of these methods return null if there is no such key in the TreeMap.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); /* * This will get the smallest key which is greater than * or equal to the specified key from the TreeMap. */ System.out.println( "Ceiling key for 3: " + tMapOddNumbers.ceilingKey(3) ); System.out.println( "Ceiling key for 4: " + tMapOddNumbers.ceilingKey(4) ); /* * This will get the entry having a key * which is greater than or equal to the specified key */ System.out.println( "Ceiling entry for 3: " + tMapOddNumbers.ceilingEntry(3) ); /* * Both these methods return null, if there is * no ceiling key */ System.out.println( tMapOddNumbers.ceilingKey(10) ); System.out.println( tMapOddNumbers.ceilingEntry(10) ); |
Output
1 2 3 4 5 |
Ceiling key for 3: 3 Ceiling key for 4: 5 Ceiling entry for 3: 3=Three null null |
What is the difference between the higherKey
and ceilingKey
methods? Well, the higherKey
method returns the key which is strictly greater than the specified key, while the ceilingKey
method returns the smallest key which is equal to or greater than the specified key.
6. How to get the key less than the specified key from the TreeMap?
Using the lowerKey and lowerEntry methods:
The lowerKey
method returns a key lower than the specified key from the TreeMap. If there is no such key, it returns null. Similarly, the lowerEntry
method returns an entry having a key which is lower than the specified key. If there is no such lower key, it returns null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); /* * This will get the key which is lower than * the specified key from the TreeMap. */ System.out.println( "Lower key for 7: " + tMapOddNumbers.lowerKey(7) ); System.out.println( "Lower key for 8: " + tMapOddNumbers.lowerKey(8) ); /* * This will get the entry having a key * which is lower than the specified key */ System.out.println( "Lower entry for 7: " + tMapOddNumbers.lowerEntry(7) ); /* * Both of these methods return null, if there is * no lower key */ System.out.println( tMapOddNumbers.lowerKey(1) ); System.out.println( tMapOddNumbers.lowerEntry(1) ); |
Output
1 2 3 4 5 |
Lower key for 7: 5 Lower key for 8: 7 Lower entry for 7: 5=Five null null |
Using the floorKey and floorEntry methods:
The floorKey
method returns the largest key which is equal to or less than the specified key. It returns null if there is no such key. Similarly, the floorEntry
method returns an entry having the largest key which is less than or equal to the specified key. This method also returns a null if there is no such key.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); /* * This will get the largest key which is equal to or lower than the * the specified key from the TreeMap. */ System.out.println( "Floor key for 7: " + tMapOddNumbers.floorKey(7) ); System.out.println( "Floor key for 8: " + tMapOddNumbers.floorKey(8) ); /* * This will get the entry having a largest key which * is equal to or lower than the specified key */ System.out.println( "Floor entry for 7: " + tMapOddNumbers.floorEntry(7) ); /* * Both these methods return null, if there is * no such key in the TreeMap */ System.out.println( tMapOddNumbers.floorKey(0) ); System.out.println( tMapOddNumbers.floorEntry(0) ); |
Output
1 2 3 4 5 |
Floor key for 7: 7 Floor key for 8: 7 Floor entry for 7: 7=Seven null null |
Difference between lowerKey and floorKey methods: The lowerKey
method returns a key which is strictly lower than the specified key while the floorKey
method returns the largest key which is equal to or lower than the specified key.
How to get the size of the TreeMap using the size method?
The size
method returns the number of entries stored in the TreeMap object. It returns 0 if the TreeMap object is empty.
1 2 3 4 5 6 7 8 9 10 11 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); //this will print 0 as the TreeMap object is empty System.out.println( "TreeMap size: " + tMap.size() ); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); //this will print 3, the number of entries in the TreeMap System.out.println( "TreeMap size: " + tMap.size() ); |
Output
1 2 |
TreeMap size: 0 TreeMap size: 3 |
How to get all the keys from TreeMap using the keySet method?
The keySet
method of the TreeMap class returns a Set view containing all the keys stored in the TreeMap object.
1 2 3 4 5 6 7 8 9 10 11 12 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); /* * To get all the keys of TreeMap, use * the keySet method */ Set<Integer> setKeys = tMap.keySet(); System.out.println("TreeMap keys: " + setKeys); |
Output
1 |
TreeMap keys: [1, 2, 3] |
The Set returned by the keySet
method is backed by the original treemap object. That means, if any of the keys is removed from the Set, it will be removed from the TreeMap too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println("TreeMap contains: " + tMap); //get all the keys from TreeMap Set<Integer> setKeys = tMap.keySet(); //remove a key from the Set setKeys.remove(1); //the key-value pair will be removed from the TreeMap too! System.out.println("TreeMap contains: " + tMap); |
Output
1 2 |
TreeMap contains: {1=One, 2=Two, 3=Three} TreeMap contains: {2=Two, 3=Three} |
How to get all the values from TreeMap using the values method?
The values
method returns a Collection view containing all the values stored in the TreeMap object. The Collection returned by this method is backed by the original map object. So any changes you make to a TreeMap object will be reflected back to the Collection, and vice versa.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println("TreeMap contains: " + tMap); /* * TO get all the values from the TreeMap * use values method */ Collection<String> collectionValues = tMap.values(); System.out.println("TreeMap all values: " + collectionValues); /* * Removing a value from the Collection will * also remove corresponding key-value pair * from the TreeMap */ collectionValues.remove("Two"); System.out.println("TreeMap contains: " + tMap); |
Output
1 2 3 |
TreeMap contains: {1=One, 2=Two, 3=Three} TreeMap all values: [One, Two, Three] TreeMap contains: {1=One, 3=Three} |
How to get all the key value pairs or entries from the TreeMap using the entrySet method?
The entrySet
method of the TreeMap class returns a Set view containing all the key-value mapping of the TreeMap object. Just like the entrySet
and values
methods, the Set returned by this method is also backed by the original treemap object. So any changes you make to the Set will also be reflected back the TreeMap object, and vice versa.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println("TreeMap contains: " + tMap); /* * To get all the mapping stored in the TreeMap, use * the entrySet method. */ Set<Map.Entry<Integer, String>> entries = tMap.entrySet(); System.out.println("TreeMap mappings: "); //iterate over the TreeMap entries for(Map.Entry<Integer, String> entry : entries){ System.out.println(entry.getKey() + " => " + entry.getValue()); } |
Output
1 2 3 4 5 |
TreeMap contains: {1=One, 2=Two, 3=Three} TreeMap mappings: 1 => One 2 => Two 3 => Three |
How to replace a value in TreeMap using the replace method?
The replace
method replaces a value mapped to a given key with the given new value, only if the given key is mapped to some value. It returns the old value which was mapped to the specified key previously, or a null if the key does not exist in the TreeMap object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println("TreeMap contains: " + tMap); /* * To replace a value mapped to a key, use the * replace method. * * It returns the old value mapped to the given key, * or null if the key was not mapped to any value */ //this will replace "One" with "NewOne" and returns "One" System.out.println( tMap.replace(1, "NewOne") ); //this will print null, as the key 5 does not exists System.out.println( tMap.replace(5, "NewFive") ); System.out.println("TreeMap contains: " + tMap); |
Output
1 2 3 4 |
TreeMap contains: {1=One, 2=Two, 3=Three} One null TreeMap contains: {1=NewOne, 2=Two, 3=Three} |
If you call the put
method with the key which already exists, it will also replace the value associated with the key with the given new value.
1 2 3 4 5 6 7 8 9 10 11 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println("TreeMap contains: " + tMap); //calling put method with the same key will also replace the value tMap.put(1, "NewOne"); System.out.println("TreeMap contains: " + tMap); |
Output
1 2 |
TreeMap contains: {1=One, 2=Two, 3=Three} TreeMap contains: {1=NewOne, 2=Two, 3=Three} |
Then what is the difference between replacing a value using the put
method and replacing a value using the replace
method? Well, the difference is, if the key does not exist in the TreeMap, the put
method creates a new key-value mapping while the replace
method does nothing and returns null.
If you want to replace a value for a given key, only if the key is mapped to a specific value, use an overloaded replace
method.
1 |
public boolean replace(K key, V oldValue, V newValue) |
The value will be replaced for a given key, if and only if the key is currently mapped to the given oldValue. This method returns true if the key-value mapping was found and oldValue is replaced with the newValue, false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println("TreeMap contains: " + tMap); /* * This will replace "Two" with "NewTwo" and * returns true, because 2 is currently mapped to * value "Two" */ System.out.println( tMap.replace(2, "Two", "NewTwo")); /* * This will not do any replacement as * the key 3 is not mapped to value "Four" and * returns false */ System.out.println( tMap.replace(3, "Four", "NewFour")); /* * This will not do any replacement as * the key 4 does not exists in the TreeMap and * returns false */ System.out.println( tMap.replace(4, "Four", "NewFour")); System.out.println("TreeMap contains: " + tMap); |
Output
1 2 3 4 5 |
TreeMap contains: {1=One, 2=Two, 3=Three} true false false TreeMap contains: {1=One, 2=NewTwo, 3=Three} |
How to check if the key is present in the TreeMap using the containsKey method?
The containsKey
method of the TreeMap class returns true if the key exists in the TreeMap, false otherwise.
1 |
public boolean containsKey(Object key) |
This method throws ClassCastException
if the given key cannot be compared with the keys contained in the TreeMap object.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); /* * To check if the key exists in the TreeMap, use * the containsKey method. */ //this will print true, as the TreeMap contains key 1 System.out.println( tMap.containsKey(1) ); //this will print false, as the TreeMap does not contain key 4 System.out.println( tMap.containsKey(4) ); |
Output
1 2 |
true false |
How to check if the value is present in the TreeMap using the containsValue method?
The containsValue
method of the TreeMap class returns true if the treemap object has the specified value mapped to one or more keys. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); /* * To check if the value exists in the TreeMap, use * the containsValue method. */ //this will print true, as the TreeMap contains value One System.out.println( tMap.containsValue("One") ); //this will print false, as the TreeMap does not contain value Four System.out.println( tMap.containsValue("Four") ); |
Output
1 2 |
true false |
How to delete a key value pair from the TreeMap?
1. Remove a key value pair using the remove method
The remove
method removes a key value mapping from the treemap object for the specified key. If the key is found in the map, it deletes the mapping and returns the value which was mapped to the key. If mapping is not found, it returns null. Although, do not rely on the null return value, as the specified key might as well be mapped to the null value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); tMap.put(4, null); /* * To remove a mapping from treemap, use * the remove method. */ //this will remove 1=>"one" mapping and returns "One" System.out.println( tMap.remove(1) ); //this will return null, as the key 5 does not exist System.out.println( tMap.remove(5) ); //this will also return null, as key 4 is mapped to null System.out.println( tMap.remove(4) ); System.out.println("TreeMap contains: " + tMap); |
Output
1 2 3 4 |
One null null TreeMap contains: {2=Two, 3=Three} |
The above given remove
method removes a key-value mapping if the specified key is mapped to any value in the TreeMap. If you want to remove the mapping only if the specified key is mapped to a specified value, then use the below given overloaded remove
method.
1 |
boolean remove(Object key, Object value) |
This method removes a mapping if and only if the specified key is mapped to the specified value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); /* * This will remove 1=>One mapping from the TreeMap, as * the key 1 is mapped to value "One" and returns true */ System.out.println( tMapOddNumbers.remove(1, "One") ); /* * This will not remove mapping having key 3, as the * key is currently not mapped to value "Four" in the TreeMap * and returns false */ System.out.println( tMapOddNumbers.remove(3, "Four") ); System.out.println("TreeMap contains: " + tMapOddNumbers); |
Output
1 2 3 |
true false TreeMap contains: {3=Three, 5=Five} |
2. Remove first key value mapping using the pollFirstEntry method
The pollFirstEntry
method removes and returns the first mapping of the TreeMap. It returns null if the TreeMap is empty.
1 2 3 4 5 6 7 8 9 10 11 12 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); /* * To remove the first mapping from the TreeMap * use the pollFirstEntry method */ System.out.println( "First entry : " + tMap.pollFirstEntry() ); System.out.println("TreeMap contains: " + tMap); |
Output
1 2 |
First entry : 1=One TreeMap contains: {2=Two, 3=Three} |
3. Remove last key value mapping using the pollLastEntry method
The pollLastEntry
method removes and returns the last mapping of the TreeMap. It returns null if the TreeMap is empty.
1 2 3 4 5 6 7 8 9 10 11 12 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); /* * To remove the last mapping from the TreeMap * use the pollLastEntry method */ System.out.println( "Last entry : " + tMap.pollLastEntry() ); System.out.println("TreeMap contains: " + tMap); |
Output
1 2 |
Last entry : 3=Three TreeMap contains: {1=One, 2=Two} |
How to check if the TreeMap is empty using the isEmpty method?
The isEmpty
method returns true if the TreeMap contains no key value pairs. It returns false otherwise.
1 2 3 4 5 6 7 8 9 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); //this will print true, as the treemap is empty System.out.println( "Is TreeMap empty?: " + tMap.isEmpty() ); tMap.put(1, "One"); //this will print false, as there is one mapping in the treemap System.out.println( "Is TreeMap empty?: " + tMap.isEmpty() ); |
Output
1 2 |
Is TreeMap empty?: true Is TreeMap empty?: false |
You can also compare the return value of the size
method with 0 to check if the TreeMap is empty instead of using the isEmpty
method. However, the isEmpty
method is a recommended way as it is more readable.
How to empty the TreeMap using the clear method?
The clear
method of the TreeMap class removes all the mappings from the TreeMap i.e. deletes all the key-value pairs or empty the TreeMap.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); System.out.println("TreeMap size: " + tMap.size()); /* * To delete all mappings from TreeMap, use * the clear method. */ tMap.clear(); System.out.println("TreeMap size: " + tMap.size()); |
Output
1 2 |
TreeMap size: 4 TreeMap size: 0 |
How to clone the TreeMap using the clone method?
The clone
method of the TreeMap class creates a shallow copy of this treemap object. The clone
method does not deep clone the TreeMap, which means the keys and values are not cloned.
1 2 3 4 5 6 7 8 9 10 11 12 |
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(); tMap.put(3, "Three"); tMap.put(1, "One"); tMap.put(2, "Two"); /* * To clone TreeMap, use the clone method. */ TreeMap<Integer, String> tMapCloned = (TreeMap<Integer, String>)tMap.clone(); System.out.println("Original TreeMap: " + tMap); System.out.println("Cloned TreeMap: " + tMap); |
Output
1 2 |
Original TreeMap: {1=One, 2=Two, 3=Three} Cloned TreeMap: {1=One, 2=Two, 3=Three} |
As you can see from the output, the original and cloned TreeMap objects contain the same key value pairs. However, since its a shallow copy, only the references to the keys and values are copied, not the actual objects. They still refer to the same objects. Refer to the below given example to understand it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
TreeMap<Integer, Empl> tMapEmployees = new TreeMap<Integer, Empl>(); tMapEmployees.put(1, new Empl(1, "Jack")); tMapEmployees.put(2, new Empl(2, "Emily")); tMapEmployees.put(3, new Empl(3, "Jay")); /* * clone the TreeMap, this will create a shallow copy * i.e. only the references of the original objects are copied * not the actual objects themselves */ TreeMap<Integer, Empl> tMapClonedEmployees = (TreeMap<Integer, Empl>) tMapEmployees.clone(); System.out.println("Original TreeMap: " + tMapEmployees); System.out.println("Cloned TreeMap: " + tMapClonedEmployees); //change any object in the original treemap Empl temp = tMapEmployees.get(1); temp.setName("ChangedName"); /* * The cloned treemap will also reflect * the changed name, as the original and cloned * treemap points to the same object */ System.out.println("Original TreeMap: " + tMapEmployees); System.out.println("Cloned TreeMap: " + tMapClonedEmployees); |
Output
1 2 3 4 |
Original TreeMap: {1=[1, Jack], 2=[2, Emily], 3=[3, Jay]} Cloned TreeMap: {1=[1, Jack], 2=[2, Emily], 3=[3, Jay]} Original TreeMap: {1=[1, ChangedName], 2=[2, Emily], 3=[3, Jay]} Cloned TreeMap: {1=[1, ChangedName], 2=[2, Emily], 3=[3, Jay]} |
How to get a submap from the TreeMap?
1. How to get the submap of TreeMap using the subMap method?
The subMap
method returns a portion of the TreeMap whose keys range from the startKey to endKey. The startKey is inclusive while the endKey is exclusive.
1 |
SortedMap<K, V> subMap(k startKey, K endKey) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); /* * To get the submap from the TreeMap, use the * subMap method and specify the key range. * * All the mappings having keys between the specified * range will be included in the submap. */ Map<Integer, String> submap = tMapOddNumbers.subMap(1, 5); /* * The startKey is inclusive, while the endKey is exclusive */ System.out.println(submap); |
Output
1 |
{1=One, 3=Three} |
The submap returned by this method is backed by the original map, so any changes you make to the submap will also be reflected back to the original TreeMap object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); Map<Integer, String> submap = tMapOddNumbers.subMap(1, 5); /* * any change in submap will be reflected * back to the original TreeMap and vice versa. */ submap.replace(1, "NewOne"); //print the TreeMap System.out.println( "TreeMap contains: " + tMapOddNumbers ); //change a value in TreeMap tMapOddNumbers.remove(2); //print the submap System.out.println("Submap contains: " + submap); |
Output
1 2 |
TreeMap contains: {1=NewOne, 3=Three, 5=Five, 7=Seven, 9=Nine} Submap contains: {1=NewOne, 3=Three} |
Plus, if you try to insert any mapping having a key that is out of the range of the submap, it throws IllegalArgumentException: key out of range exception.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); Map<Integer, String> submap = tMapOddNumbers.subMap(1, 5); /* * This will throw IllegalArgumentException * as the key 6 is not in the range of 1 to 5 */ submap.putIfAbsent(6, "Six"); |
Output
1 2 3 |
Exception in thread "main" java.lang.IllegalArgumentException: key out of range at java.util.TreeMap$NavigableSubMap.put(Unknown Source) at java.util.Map.putIfAbsent(Unknown Source) |
In the above given submap method, the startKey is inclusive while the endKey is exclusive. If you want to change the startKey or endKey being inclusive or exclusive, you can use an overloaded subMap
method.
1 |
NavigableMap<K, V> subMap(K startKey, boolean startKeyInclusive, K endKey, boolean endKeyInclusive) |
The startKeyInclusive and endKeyInclusive parameters control the inclusiveness or exclusiveness of the start and end keys. If the startKeyInclusive parameter is true, the startKey becomes inclusive. If it is false, the startKey becomes exclusive. The same applies to the endKey and endKeyInclusive parameters.
2. Get the submap having keys greater than the specified key using the tailMap method
The tailMap
method returns a submap or portion of the TreeMap whose keys are greater than or equal to the specified key. The submap returned from this method is backed by the original TreeMap, so any changes you make in the submap will be reflected back to the TreeMap, and vice versa.
1 |
public SortedMap<K, V> tailMap(k fromKey) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); /* * To get a submap having keys greater than or equal to * the specified key, use the tailMap method. */ //this will return submap having keys >= 5 Map<Integer, String> tailmap = tMapOddNumbers.tailMap(5); System.out.println(tailmap); |
Output
1 |
{5=Five, 7=Seven, 9=Nine} |
Similar to the map obtained using the submap method, If you try to put a key which is out of the range of the submap, it throws IllegalArgumentException: key out of range exception.
There is an overloaded tailMap
method that has an additional parameter that controls the inclusiveness of the fromKey.
1 |
public NavigableMap<K, V> tailMap(K fromKey, boolean fromKeyInclusive) |
If the fromKeyInclusive parameter is true, the submap will have the keys greater than or equal to the fromKey. If it is false, the submap will have keys greater than the specified fromKey.
3. Get the submap having keys less than the specified key using the headMap method
Similar to the tailMap
method, the headMap
method returns a submap having keys strictly less than the specified key. The submap returned from this method is backed by the original TreeMap, so any changes you make in the submap will be reflected back to the TreeMap, and vice versa.
1 |
public SortedMap<K, V> headMap(K toKey) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); /* * To get a submap having keys strictly less than * the specified key, use the headMap method. */ //this will return submap having keys < 7 Map<Integer, String> headmap = tMapOddNumbers.headMap(7); System.out.println(headmap); |
Output
1 |
{1=One, 3=Three, 5=Five} |
Use an overloaded headMap
method to control the inclusiveness of the toKey parameter.
1 |
public NavigableMap<K, V> headMap(K toKey, boolean toKeyInclusive) |
If the toKeyInclusive parameter is true, the toKey is included in the submap returned by this method. If it is false, only keys less than the specified keys will be included in the submap. Both of these methods throw IllegalArgumentException: key out of range exception if you try to put a key-value pair having the key out of the range of the submap.
How to iterate TreeMap in Java?
The TreeMap tutorial is incomplete without learning how to iterate the TreeMap. There are several ways to iterate through the TreeMap object.
1. How to iterate through keys of TreeMap?
The keySet
method returns the Set view of the keys stored in the TreeMap object. We can iterate the key Set using the enhanced for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); //get all the keys Set<Integer> keys = tMapOddNumbers.keySet(); System.out.println("Iterate TreeMap keys:"); //use enhanced for loop to iterate TreeMao keys for(Integer key : keys){ System.out.println(key); } |
Output
1 2 3 4 5 6 |
Iterate TreeMap keys: 1 3 5 7 9 |
2. How to iterate through the values of TreeMap?
The values
method returns a Collection view of all the values stored in the TreeMap object. We can iterate through the values using the enhanced for loop just like iterating the keys.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); //get all the values Collection<String> values = tMapOddNumbers.values(); System.out.println("Iterate TreeMap values:"); //use enhanced for loop to iterate TreeMap values for(String value : values){ System.out.println(value); } |
Output
1 2 3 4 5 6 |
Iterate TreeMap values: One Three Five Seven Nine |
3. How to iterate through key-value pairs of TreeMap?
The entrySet
method returns the Set view of the entries i.e. key-value pairs stored in the TreeMap object. We can iterate through the TreeMap entries using enhanced for loop, while loop, or for loop.
Iterate TreeMap using enhanced for loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); //get the entry set Set<Map.Entry<Integer, String>> entries = tMapOddNumbers.entrySet(); System.out.println("Iterate TreeMap mappings: "); for(Map.Entry<Integer, String> entry : entries){ System.out.println(entry.getKey() + " => " + entry.getValue()); } |
Output
1 2 3 4 5 6 |
Iterate TreeMap mappings: 1 => One 3 => Three 5 => Five 7 => Seven 9 => Nine |
Iterate TreeMap using while loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); //get the entry set Set<Map.Entry<Integer, String>> entries = tMapOddNumbers.entrySet(); //get the iterator for entry set Iterator<Entry<Integer, String>> iterator = entries.iterator(); System.out.println("Iterate TreeMap using while loop: "); //use while loop to iterate while(iterator.hasNext()){ Entry<Integer, String> entry = iterator.next(); System.out.println(entry.getKey() + " => " + entry.getValue()); } |
Output
1 2 3 4 5 6 |
Iterate TreeMap using while loop: 1 => One 3 => Three 5 => Five 7 => Seven 9 => Nine |
Iterate TreeMap using for loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
TreeMap<Integer, String> tMapOddNumbers = new TreeMap<Integer, String>(); tMapOddNumbers.put(1, "One"); tMapOddNumbers.put(3, "Three"); tMapOddNumbers.put(5, "Five"); tMapOddNumbers.put(7, "Seven"); tMapOddNumbers.put(9, "Nine"); //get the entry set Set<Map.Entry<Integer, String>> entries = tMapOddNumbers.entrySet(); //get the iterator for entry set Iterator<Entry<Integer, String>> iterator = entries.iterator(); System.out.println("Iterate TreeMap using for loop: "); //use for loop to iterate for( ; iterator.hasNext() ; ){ Entry<Integer, String> entry = iterator.next(); System.out.println(entry.getKey() + " => " + entry.getValue()); } |
Output
1 2 3 4 5 6 |
Iterate TreeMap using for loop: 1 => One 3 => Three 5 => Five 7 => Seven 9 => Nine |
The below given additional Java TreeMap examples discuss the concepts in more detail.
Java TreeMap Examples
- How to convert TreeMap to HashMap
- How to create a new TreeMap object in Java (TreeMap constructors)
- How to print TreeMap in Java
- How to get the size of the TreeMap
- How to check if the TreeMap is empty
- How to fix java.lang.ClassCastException – cannot be cast to java.lang.Comparable while adding entries to the TreeMap
- How to get all keys from the TreeMap
- How to get all values from the TreeMap
- How to check if the key exists in the TreeMap (TreeMap contains a key)
- How to check if the value exists in the TreeMap (TreeMap contains a value)
- How to remove all entries or clear TreeMap in Java
- How to get value from TreeMap using the key (TreeMap get method)
- How to add key-value mapping to the TreeMap (TreeMap put method)
- How to replace a value for the given key in the TreeMap (TreeMap replace method)
- Java TreeMap forEach example
- How to iterate TreeMap in Java
- How to iterate Java TreeMap in reverse order
- How to get TreeMap key or TreeMap value using index
- How to get TreeMap key using the value in Java
- How to compare two TreeMap objects in Java
- How to convert Java TreeMap to an ArrayList (List)
- How to get last key, last value, or last entry from the Java TreeMap
- How to get submap, headmap, and tailmap from Java TreeMap
- How to remove the first entry or last entry from the Java TreeMap
- How to get TreeMap key, value or entry greater than or less than the specified key
References:
Java TreeMap class Javadoc
Please let me know if you liked the Java TreeMap tutorial with examples in the comments section below.