How to Get Keys from Map in Java Example

Get Keys from Map in Java

In this example, We will show you simple program about, How to get keys from map in Java. The example has been tested and shared in the same post.

Example Program

package com.dineshkrish;

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

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class GetKeys {

	public static void main(String[] args) {
		
		// defining map object
		Map<Integer, String> map = new TreeMap<Integer, String>();
		
		// adding elements to map
		map.put(1, "One");
		map.put(2, "Two");
		map.put(3, "Three");
		map.put(4, "Four");
		map.put(5, "Five");
		map.put(6, "Six");
		map.put(7, "Seven");
		map.put(8, "Eight");
		map.put(9, "Nine");
		map.put(10, "Ten");
		
		// getting only keys form map
		Set<Integer> keys = map.keySet();
		
		// printing the set of keys
		System.out.println(keys);
		
	}
	
}

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

References

1. Java Set Interface
2. Java Map Interface
3. Java TreeMap Class
4. Java Map keySet() method