This Java Example shows how to retrieve all keys contained in TreeMap using keySet method of Java TreeMap class.
import java.util.Set; import java.util.TreeMap; public class GetKeysFromTreeMapExample { public static void main(String[] args) { // create object of TreeMap TreeMap phoneBook = new TreeMap(); // Adding key value pairs to TreeMap phoneBook.put("John", "245745"); phoneBook.put("Joy", "245786"); phoneBook.put("Roy", "233783"); /** * Set keySet() - Returns a set view of the keys * contained in this map in ascending order. **/ Set nameSet = phoneBook.keySet(); System.out.println("Names in the phone book are :"); for (Object name : nameSet) { System.out.println("Name: " + name); } } }
The output is:
Names in the phone book are :
Name: John
Name: Joy
Name: Roy
No comments:
Post a Comment