Sunday, October 26, 2014

Java Program to demonstrate TreeMap


TreeMapExample.java:
import java.util.TreeMap;

public class TreeMapExample {

   public static void main(String[] args) {
       TreeMap vehicles = new TreeMap();
       
       // Add some vehicles.
       vehicles.put("BMW", 5);
       vehicles.put("Mercedes", 3);
       vehicles.put("Audi", 4);
       vehicles.put("Ford", 10);
       
       System.out.println("Total vehicles: " + vehicles.size());
       
       // Iterate over all vehicles, using the keySet method.
       for(String key: vehicles.keySet())
           System.out.println(key + " - " + vehicles.get(key));
       System.out.println();
       
       System.out.println("Highest key: " + vehicles.lastKey());
       System.out.println("Lowest key: " + vehicles.firstKey());
       
       System.out.println("\nPrinting all values:");
       for(Integer val: vehicles.values())
           System.out.println(val);
       System.out.println();
       
       // Clear all values.
       vehicles.clear();
       
       // Equals to zero.
       System.out.println("After clear operation, size: " + vehicles.size());
   }
}
A sample execution is shown below:
Total vehicles: 4
Audi - 4
BMW - 5
Ford - 10
Mercedes - 3

Highest key: Mercedes
Lowest key: Audi

Printing all values:
4
5
10
3

After clear operation, size: 0

No comments:

Post a Comment