The following program demonstrates An Example of TreeMap in Java.

In the following program, we create a TreeMap using the specified key-value pairs. Furthermore, the keys are of the type Staff, which is a user-defined type. Similarly, the values are of type Double which represents the salaries of the Staff. Since the type of the key is a user-defined type we need to implement the Comparable interface in the class Staff. Because TreeMap is an ordered collection, we need to do this.

package com.treemaps;
import java.util.*;
public class TreeMapDemo {
	public static void main(String[] args) {
			// TODO Auto-generated method stub
			TreeMap<Staff, Double> htb=new TreeMap<Staff, Double>();
			htb.put(new Staff(101, "Jim"), 12000.0);
			htb.put(new Staff(102, "Jill"), 14000.0);
			htb.put(new Staff(103, "Joe"), 24000.0);
			htb.put(new Staff(104, "Joe"), 34000.0);
			htb.put(new Staff(102, "Jill"),5000.0);
			htb.put(new Staff(101, "Jim"), 19000.0);
			
			System.out.println("Elements in Hashtable: ");
			Set entrySet=htb.entrySet();
			Iterator it=entrySet.iterator();
			while(it.hasNext())
			{
				Map.Entry<Staff, Double> me=(Map.Entry<Staff, Double>)(it.next());
				System.out.println("Key: "+me.getKey()+", Value: "+me.getValue());
			}
		}
	}
	/*
	 * 
	 */
	class Staff implements Comparable<Staff>
	{
		int staff_id;
		String sname;

		public int compareTo(Staff s)
		{
			if(staff_id==s.getStaff_id())
				return 0;
			else
				if(staff_id<s.getStaff_id())
					return -1;
				else
					return 1;
		}
		public Staff(int staff_id, String sname) {
			super();
			this.staff_id = staff_id;
			this.sname = sname;
		}
		public int getStaff_id() {
			return staff_id;
		}
		public void setStaff_id(int staff_id) {
			this.staff_id = staff_id;
		}
		public String getSname() {
			return sname;
		}
		public void setSname(String sname) {
			this.sname = sname;
		}
		@Override
		public String toString() {
			return "Staff Details: [staff_id=" + staff_id + ", sname=" + sname + "]";
		}	
}

Output

Demonstrating An Example of TreeMap in Java
Demonstrating An Example of TreeMap in Java

Further Reading

Java Practice Exercise

programmingempire

Princites