Here we will learn how to iterate through the values contained in the TreeMap object.
Source Code
package com.beginner.examples;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;
public class IterateValuesOfTreeMap {
public static void main(String[] args) {
//create TreeMap.
TreeMap treeMap = new TreeMap();
treeMap.put("1", "Alice");
treeMap.put("2", "Bob");
treeMap.put("3", "Jack");
/*
* To get Collection of values contained in TreeMap use values method of TreeMap.
*/
Collection collection = treeMap.values();
Iterator iterator = collection.iterator();
System.out.println("TreeMap contains :");
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Output:
TreeMap contains :
Alice
Bob
Jack
References
Imported packages in Java documentation: