How to Initialize TreeMap with values in Java?

This example shows how to initialize TreeMap with values  in Java.  .This example also shows How to Initialize TreeMap In Java inline using constructor and Anonymous Subclass .

How to Initialize TreeMap with values in Java?

Now We will discuss several ways for initialize TreeMap with values as following .

    1. Initialize TreeMap Using Constructor

We can initialize using constructor We have four type TreeMap Constructor . .

import java.util.HashMap;
import java.util.TreeMap;

public class TreeMapExample {
	
	public static void main(String[] args) {
		
		 HashMap<String, String> hashMap = new HashMap<String, String>();
		 hashMap.put("hcl", "amit");
		 hashMap.put("tcs","ravi");
		 hashMap.put("wipro","anmol");
		
	       TreeMap<String, String> treeMap = new TreeMap<String,String>(hashMap);
		System.out.println("treeMap is ="+ treeMap);	
		}
		
}

Output :

treeMap is ={hcl=amit, tcs=ravi, wipro=anmol}

Anonymous Subclass to Create TreeMap

We can create map with the help of anonymous subclass .
But we should avoid this way to create TreeMap because first we create anonymous class here then TreeMap ,it might me create problem of memory leak.

import java.util.TreeMap;

public class TreeMapExample {
	
	public static void main(String[] args) {
		
		TreeMap<String, String> treeMap = new TreeMap<String, String>() {{
			put("hcl", "amit");
			put("tcs","ravi");
			put("wipro","anmol");
		}};
			
			System.out.println("treeMap is ="+ treeMap);	
		}
		
}

Output :

treeMap is ={hcl=amit, tcs=ravi, wipro=anmol}

Use the Double brace initialization to create HashMap with values we should avoid. This example is part of Java TreeMap Example

Reference

Java Doc – TreeMap

Leave a Reply

Your email address will not be published. Required fields are marked *

4 + 5 =