This Java Example shows how to iterate through the values contained in the TreeMap object.
import java.util.Collection;
import java.util.TreeMap;
import java.util.Iterator;
public class IterateValuesOfTreeMapExample {
public static void main(String[] args) {
// create TreeMap object
TreeMap tMap = new TreeMap();
// add key value pairs to TreeMap
tMap.put("1", "One");
tMap.put("2", "Two");
tMap.put("3", "Three");
/**
values() - Returns a collection view of the values contained
in this map. The collection's iterator will return the values
in the order that their corresponding keys appear in the tree.
The collection is backed by this TreeMap instance, so changes
to this map are reflected in the collection, and vice-versa
**/
Collection c = tMap.values();
// obtain an Iterator for Collection
Iterator itr = c.iterator();
System.out.println("The map contains values...");
// iterate through TreeMap values iterator
while (itr.hasNext())
System.out.println(itr.next());
}
}
The output is:
The map contains values...
One
Two
Three
No comments:
Post a Comment