TreeMap
TreeMap
Key points:
- TreeMap is an implementation class of SortedMap.
- It arranges the key-value pair in a sorted manner based on the key.
Example:
package com.quipoin;
public class Student implements Comparable<Student>{
int id;
String name;
public Student(int id, String name) {
this.id=id;
this.name=name;
}
@Override
public String toString() {
return id+"\t"+name;
}
@Override
public int compareTo(Student std) {
return this.id-std.id;
}
}
package com.quipoin;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class TestStudent {
public static void main(String[] args) {
Student s1=new Student(1011, "Prabhas");
Student s2=new Student(1018, "Salman");
Student s3=new Student(1013, "Aryan");
Student s4=new Student(1016, "Pooja");
TreeMap<Student, String> tm=new TreeMap<>();
//Storing student object as key and their favorite language as the value
tm.put(s1, "Java");
tm.put(s2, "SQL");
tm.put(s3, "Python");
tm.put(s4, "C++");
System.out.println("Student details!!");
System.out.println("----------------------------");
System.out.println("Id\tName\tFav_Language");
System.out.println("----------------------------");
Set<Student> student=tm.keySet();
Iterator<Student> it=student.iterator();
while(it.hasNext()) {
Student key=it.next();
String value=tm.get(key);
System.out.println(key+"\t"+value);
}
}
}
Output:
Student details!!
----------------------------
Id Name Fav_Language
----------------------------
1011 Prabhas Java
1013 Aryan Python
1016 Pooja C++
1018 Salman SQL