TreeMap is a part of Java Collection framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot have a null key but can have multiple null values. TreeMap is not synchronized, we have to synchronize it explicitly in order to use it in a multi threading environment. TreeMap maintains the ascending order of the elements.
The way to convert TreeMap to ArrayList:
- TreeMap having keys and values can be converted into two ArrayLists of keys and values.
- Also two ArrayLists, one with keys and the other with values, can be converted into a TreeMap.
Example:
TreeMap : {1=Welcome, 2=To, 3= Geeks, 4=For, 5=Geeks}
keyList : [1, 2, 3, 4, 5]
valueList : [Welcome, To, Geeks, For, Geeks]
Approach:
- Create a TreeMap object and insert some keys and values.
- Extract the keys from the TreeMap using TreeMap.keySet() method and put them into an ArrayList object which has been created for storing keys.
- Extract the values from the TreeMap using TreeMap.values() method and put them into another ArrayList object which has been created for storing values.
Java
// Java program to demonstrate conversion of // TreeMap to ArrayList import java.util.*; class GFG { // a class level treeMap object static TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Method to convert TreeMap to ArrayList static void convertMapToList() { // Extract the keys from the TreeMap // using TreeMap.keySet() and // assign them to keyList of type ArrayList ArrayList<Integer> keyList = new ArrayList<Integer>(treeMap.keySet()); // Extract the values from the TreeMap // using TreeMap.values() and // assign them to valueList of type ArrayList ArrayList<String> valueList = new ArrayList<String>(treeMap.values()); // printing the keyList System.out.println( "List of keys of the given Map : " + keyList); // printing the valueList System.out.println( "List of values of the given Map : " + valueList); } // Driver Method public static void main(String args[]) { // inserting data into the TreeMap // using TreeMap.put() method treeMap.put(1, "Welcome"); treeMap.put(2, "To"); treeMap.put(3, "Geeks"); treeMap.put(4, "For"); treeMap.put(5, "Geeks"); // printing the TreeMap System.out.println("The TreeMap is : " + treeMap); // calling convertMapToList() method convertMapToList(); } } |
The TreeMap is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}
List of keys of the given Map : [1, 2, 3, 4, 5]
List of values of the given Map : [Welcome, To, Geeks, For, Geeks]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

