TreeMap in Java
The TreeMap class implements the Map interface which store key-value pairs in tree data structure. It provides an efficient means of storing key/values pairs in sorted order.
Followings are the features of TreeMap.
- It contains only unique elements.
- It can’t have null key but can have multiple null values.
- It is not synchronized i.e not safe for multi-threaded application.
- It is same as HashMap instead maintains ascending order.
TreeMap provides following constructors.
[table “” not found /]Example of TreeMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.code2succeed.collection; import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { TreeMap treeMap = new TreeMap(); treeMap.put(1, "value1"); treeMap.put(4, "value4"); treeMap.put(10, "value10"); treeMap.put(5, "value5"); treeMap.put(2, "value2"); System.out.println(treeMap); //retrieving submap System.out.println(treeMap.headMap(4)); System.out.println(treeMap.headMap(6)); System.out.println("Poll first entry of TreeMap : "+treeMap.pollFirstEntry()); System.out.println("Content of TreeMap after polling first entry: "+treeMap); } } |
Output
1 2 3 4 5 |
{1=value1, 2=value2, 4=value4, 5=value5, 10=value10} {1=value1, 2=value2} {1=value1, 2=value2, 4=value4, 5=value5} Poll first entry of TreeMap : 1=value1 Content of TreeMap after polling first entry: {2=value2, 4=value4, 5=value5, 10=value10} |