Browse the keys of a TreeMap in Java

In this tutorial we will learn how to browse and retrieve the keys of a TreeMap in Java. For more details, I suggest you read the article how to navigate a TreeMap in Java.

The TreeMap class provides a predefined method that helps us directly get the set of keys:

public Set< k> keySet(): The method  keySet()  is used to return a Set object that contains all the keys in that map. Iteration with  Iterator  of the Set returns the keys in ascending order. The set is returned by the map, so any changes in the map are also made in the set and vice versa.

This example shows how to retrieve all keys from a TreeMap. You can have all key entries as a Set object by calling the keySet().

import java.util.Set; 
import java.util.TreeMap;

public class TreeMapgetallKeys {
public static void main(String[] args) {
TreeMap< String, Integer> treemap = new TreeMap< String, Integer> ();

// Add key-value pairs to TreeMap
treemap.put("key1",12);
treemap.put("key2",21);
treemap.put("key3",45);
treemap.put("key4",14);
treemap.put("key5",87);

//display treemap
System.out.println(treemap);

//retrieve all keys
Set< String> keys = treemap.keySet();
for(String key: keys){
System.out.println(key);
}
}
}
Output:

{key1=12, key2=21, key3=45, key4=14, key5=87}
key1
key2
key3
key4
key5
Example 2:

import java.util.*; 

public class keySet {
public static void main(String[] args) {
// creating TreeMap
TreeMap< Integer, String> treemap = new TreeMap< Integer, String> ();

// insert in treemap
treemap.put(4, "four");
treemap.put(6, "six");
treemap.put(1, "one");
treemap.put(8, "eight");
treemap.put(3, "three");

// creating a set
Set set=treemap.keySet() object;

// get the contents of the set
System.out.println("key list: "+set) object;

//creating an Iterator
Iterator iterator = set.iterator();

//browse keys with Iterator
System.out.println("Browse with Iterator");
while(iterator.hasNext()){
int key = ((int) iterator.next());
System.out.println(key);
}
}
}
Running this code results like this:

key list: [1, 3, 4, 6, 8]
Browse with Iterator
1
3
4
6
8
References:
TutorialsPoint:  java.util.TreeMap.keySet() Method
Java documentation: the keySet()