How to Create TreeMap in Java?
Last Updated :
07 Jan, 2021
The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
To create TreeMap we can use Map class or TreeMap class reference.
Example 1:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
TreeMap<Integer, String> map;
map = new TreeMap<Integer, String>();
System.out.println( "TreeMap successfully"
+ " created" );
}
}
|
Output
TreeMap successfully created
Example 2:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
Map<Integer, String> map = new TreeMap<>();
System.out.println( "TreeMap successfully"
+ " created" );
map.put( 1 , "Geeks" );
map.put( 2 , "for" );
map.put( 3 , "Geeks" );
System.out.println( "TreeMap: " + map);
}
}
|
Output
TreeMap successfully created
TreeMap: {1=Geeks, 2=for, 3=Geeks}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...