Java – TreeMap class

Previous
Next

TreeMap :
• TreeMap maintains ascending order of keys.
• TreeMap does it through Balanced binary trees.

import java.util.*;
class MapDemo 
{
	public static void main(String[] args) 
	{
		TreeMap tm = new TreeMap();
		tm.put(26, "one");
		tm.put(16, "two"); 
		//tm.put(null,"three"); //not allowed
		//tm.put("str","four");  //not allowed
		System.out.println(tm);
	}
}
  • HashMap doesn’t maintain insertion order
import java.util.*;
class MapDemo 
{
	public static void main(String[] args) 
	{
		int keys[ ] = {50,40,30,20,10};
		String vals[ ] = {"java" , "Python" , "C" , "C#" , "Android"};

		HashMap map = new HashMap();
		for (int i=0 ; i<keys.length ; i++)
		{
			int key = keys[i];
			String val = vals[i];
			map.put(key,val);
		}
		System.out.println("Hash Map is : " + map);  // random order....
	}
}

Linked HashMap maintains insertion order.

import java.util.*;
class MapDemo 
{
	public static void main(String[] args) 
	{
		int keys[ ] = {50,40,30,20,10};
		String vals[ ] = {"java" , "Python" , "C" , "C#" , "Android"};

		LinkedHashMap map = new LinkedHashMap();
		for (int i=0 ; i<keys.length ; i++)
		{
			int key = keys[i];
			String val = vals[i];
			map.put(key,val);
		}
		System.out.println("Linked Hash Map is : " + map);  // insertion order....
	}
}

TreeMap maintains Sorted order using keys.

import java.util.*;
class MapDemo 
{
	public static void main(String[] args) 
	{
		int keys[ ] = {50,40,30,20,10};
		String vals[ ] = {"java" , "Python" , "C" , "C#" , "Android"};

		TreeMap map = new TreeMap();
		for (int i=0 ; i<keys.length ; i++)
		{
			int key = keys[i];
			String val = vals[i];
			map.put(key,val);
		}
		System.out.println("TreeMap is : " + map);  // sorted order....
	}
}

Reading and Storing Account type objects into Map collection

import java.util.*;
class Account
{
	int accno ;
	int balance ;
	Account(int accno , int balance)
	{
		this.accno = accno ;
		this.balance = balance ;
	}
}
class MapDemo 
{
	public static void main(String[] args) 
	{
		HashMap map = new HashMap();
		Scanner scan = new Scanner(System.in);

		System.out.println("Enter 5 account details : ");
		for(int i=0 ; i<5 ; i++)
		{
			int no = scan.nextInt();
			int bal = scan.nextInt();
			Account obj = new Account(no, bal);
			map.put(no, obj);
			System.out.println("Record added...");
		}

		System.out.println("Enter accno to display details : ");
		int no = scan.nextInt();

		Account acc = (Account)map.get(no);
		System.out.println("Balance is : " + acc.balance);
	}
}
Previous
Next

Add Comment

Courses Enquiry Form