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; publicclass TreeMapExample { publicstaticvoid main(String[] args) { Map<Integer, String> map = new TreeMap<Integer, String>(); // Add Items to the TreeMap map.put(newInteger(1), "One"); map.put(newInteger(2), "Two"); map.put(newInteger(3), "Three"); map.put(newInteger(4), "Four"); map.put(newInteger(5), "Five"); map.put(newInteger(6), "Six"); map.put(newInteger(7), "Seven"); map.put(newInteger(8), "Eight"); map.put(newInteger(9), "Nine"); map.put(newInteger(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(newInteger(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