Searching...
Saturday, 6 October 2012

Java Map: TreeMap Example

09:12
·         Tree based implementation of the SortedMap interface
·         The keys are ordered according to their natural order
·         Less efficient than HashMap for insertion and mapping
·         Its methods are not synchronized
 

Example

package mycollectiontest;

import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

public class CollectionExample {

public static void main(String[] args) {
TreeMap<String, String> treeMap = new TreeMap<String, String>();

// add key value pairs
treeMap.put("1", "Java");
treeMap.put("2", ".Net");
treeMap.put("3", "Oracle");
treeMap.put("4", "PHP");
treeMap.put("5", "MainFrame");
treeMap.put("6", "C++");

Collection<String> c = treeMap.values();

// Iterating
Iterator<String> itr = c.iterator();

// iterate through TreeMap values iterator
while (itr.hasNext())
System.out.println("TreeMap element " + itr.next());
}

}

Output

TreeMap element Java
TreeMap element .Net
TreeMap element Oracle
TreeMap element PHP
TreeMap element MainFrame
TreeMap element C++

0 comments: