Sunday 3 June 2018

TreeMap Example with User Defined Object as Key

TreeMap Example


A Red-Black tree based NavigableMap implementation. 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. This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

TreeMap Hierarchy



Here Student is a class which is user defined class, so for natural order of sorting I have implemented comparable interface and overridden compareTo() method.


package com.gaurav.mapexample;

import java.util.Map;
import java.util.TreeMap;

class Student implements Comparable<Student>{
private String name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}

@Override
public int compareTo(Student student) {
if(this.age > student.getAge())
return 1;
else if(this.age< student.getAge())
return -1;
else return 0;
}

}

public class TreeMapExample {
public static void main(String args[]) {
Map<Student, String> treeMapStudent = new TreeMap<Student, String>();
treeMapStudent.put(new Student("Gaurav", 38), "1st Div");
treeMapStudent.put(new Student("Shivam", 15), "2nd Div");
treeMapStudent.put(new Student("Aaditya", 8), "1st Div");

treeMapStudent.put(new Student("Ajit", 45), "3rd Div");

for(Map.Entry<Student, String> entry: treeMapStudent.entrySet()){
System.out.println("Keys are:-"+entry.getKey()+" Values are:-"+entry.getValue());
}

}
}

Output

Keys are:-Student [name=Aaditya, age=8] Values are:-1st Div
Keys are:-Student [name=Shivam, age=15] Values are:-2nd Div
Keys are:-Student [name=Gaurav, age=38] Values are:-1st Div
Keys are:-Student [name=Ajit, age=45] Values are:-3rd Div


No comments:

Post a Comment