Use Generic TreeMap to store Integer as key and String as value : TreeMap « Collections Data Structure « Java






Use Generic TreeMap to store Integer as key and String as value

 

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapExample {
  public static void main(String[] args) {
    Map<Integer, String> map = new TreeMap<Integer, String>();

    // Add Items to the TreeMap
    map.put(new Integer(1), "One");
    map.put(new Integer(2), "Two");
    map.put(new Integer(3), "Three");
    map.put(new Integer(4), "Four");
    map.put(new Integer(5), "Five");
    map.put(new Integer(6), "Six");
    map.put(new Integer(7), "Seven");
    map.put(new Integer(8), "Eight");
    map.put(new Integer(9), "Nine");
    map.put(new Integer(10), "Ten");

    // Use iterator to display the keys and associated values
    System.out.println("Map Values Before: ");
    Set keys = map.keySet();
    for (Iterator i = keys.iterator(); i.hasNext();) {
      Integer key = (Integer) i.next();
      String value = (String) map.get(key);
      System.out.println(key + " = " + value);
    }

    // Remove the entry with key 6
    System.out.println("\nRemove element with key 6");
    map.remove(new Integer(6));

    // Use iterator to display the keys and associated values
    System.out.println("\nMap Values After: ");
    keys = map.keySet();
    for (Iterator i = keys.iterator(); i.hasNext();) {
      Integer key = (Integer) i.next();
      String value = (String) map.get(key);
      System.out.println(key + " = " + value);
    }
  }
}

   
  








Related examples in the same category

1.TreeMap
2.Read file content and save to a TreeMap
3.Get Synchronized Map from Java TreeMap
4.Check if a particular key exists in Java TreeMap
5.Get Set view of Keys from Java TreeMap
6.Get Tail Map from Java TreeMap
7.Get Size of Java TreeMap
8.Remove value from Java TreeMap
9.Iterate through the values of Java TreeMap
10.Check if a particular value exists in Java TreeMap
11.Remove all values from Java TreeMap
12.Get Sub Map from Java TreeMap
13.Get lowest and highest key stored in Java TreeMap
14.Get Head Map from Java TreeMap