public static void specialFunctions(String args[])
{
TreeMap<String, Integer> tm1 = new TreeMap<String, Integer>();
tm1.put("banana", 20);
tm1.put("apple", 50);
tm1.put("melon", 40);
tm1.put("guava", 20);
tm1.put("cherry", 30);
System.out.println("\nElements of tm1: " + tm1);
Set mySet = tm1.keySet();
System.out.println("Keys of tm1: " + mySet);
Collection myCol = tm1.values();
System.out.println("Values of tm1: " + myCol);
// USING ITERATOR
System.out.print("\nPrinting keys with Iterator: ");
Iterator it1 = mySet.iterator();
while(it1.hasNext())
{
System.out.print(it1.next() + ", ");
}
// TREEMAP SORT BY VALUE
TreeSet yourSet = new TreeSet();
yourSet.addAll(myCol);
System.out.println("\nTreeMap sort by value: " + yourSet);
// COMPARING TWO TREE MAPS
TreeMap<String, Integer> tm2 = new TreeMap<String, Integer>();
tm2.putAll(tm1);
System.out.println("\nElements of tm2: " + tm2);
if(tm1.equals(tm2))
{
System.out.println("tm1 and tm2 contain same elements\n");
}
System.out.println("\t\tEXTRACTING TREEMAP ELEMENTS\n");
SortedMap m1 = tm1.subMap("banana", "guava");
System.out.println("subMap(\"banana\", \"guava\"): " + m1);
SortedMap m2 = tm1.headMap("guava");
System.out.println("headMap(\"guava\"): " + m2);
SortedMap m3 = tm1.tailMap("guava");
System.out.println("tailMap(\"guava\"): " + m3);
}
Thursday, 19 January 2012
TreeMap Program - Special functions
Labels:
Collections,
treeMap
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment