TreeMap Example Java Program


Maps are defined by the java.util.Map interface in Java. Maps are simple data structures that associate a key with a value. The element is the value. This lets the map be very flexible. If the key is the hash code of the element, the map is essentially a set. If it's just an increasing number, it becomes a list. Methods can be called that find the key or map entry that's closest to the given key in either direction. The map can also be reversed, and an iterator in reverse order can be generated from it. It's implemented by java.util.TreeMap.


TreeMap marks = new TreeMap();

TreeMap Example Program

import java.util.TreeMap;
public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap marks = new TreeMap();
        marks.put("Student1", 120);
        marks.put("Student2", 190);
        marks.put("Student3", 89);
        marks.put("Student4", 142);
        for(String key: marks.keySet()){
			System.out.println(key  +" : "+ marks.get(key));

Sample Output

Output is:
Student1 : 120
Student2 : 190
Student3 : 89
Student4 : 142