How to Get Set of Keys from Java TreeMap


The example aims to get set of keys contained in TreeMap by keySet method in Java.

Source Code

package com.beginner.examples;

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

public class GetSetViewOfKeysFromTreeMap {

	public static void main(String[] args) {
		
		//create TreeMap.
		TreeMap treeMap = new TreeMap();
		
		treeMap.put("1","Alice");
		treeMap.put("2","Bob");
		treeMap.put("3","Jack");
		
		/*
		 * get Set of keys contained in TreeMap using keySet method of TreeMap.
		 */
		Set set = treeMap.keySet();
		
		System.out.println("Set contains : ");
		
		Iterator iterator = set.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}

	}

}

Output:

Set contains : 
1
2
3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments