TreeMap in java
TreeMap
TreeMap stores entries of key-value pair in natural sorting order of keys. So, if Keys are Strings, it will maintain alphabetical order. If keys are integers, it will keep numbers in increasing order.
Let’s consider the same above example with TreeMap. This time, Footballers will be sorted based on their ids.
Footballer.java
package com.javatrainingschool;
public class Footballer {
private int id;
private String name;
public Footballer(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Footballer [id=" + id + ", name=" + name + "]";
}
//getter and setter methods
}
TreeMapExample.java
package com.javatrainingschool;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class TreeMapExample {
public static void main(String[] args) {
Footballer f1 = new Footballer(1, "Christiano Ronaldo");
Footballer f2 = new Footballer(2, "Lionel Messi");
Footballer f3 = new Footballer(3, "Pele");
Footballer f4 = new Footballer(4, "Diego Maradona");
Map<Integer, Footballer> map = new TreeMap<Integer, Footballer>();
map.put(4, f4);
map.put(2, f2);
map.put(1, f1);
map.put(3, f3);
//entries will be printed in the order Maradona, Messi, Ronaldo, and Pele
for(Entry<Integer, Footballer> entry : map.entrySet()) {
System.out.println(entry.getValue());
}
}
}
Output :
Footballer [id=1, name=Christiano Ronaldo]
Footballer [id=2, name=Lionel Messi]
Footballer [id=3, name=Pele]
Footballer [id=4, name=Diego Maradona]