HashMap keySet() Method in Java

Published by user on

The keySet() method of HashMap returns a set of keys contained in it. Any changes to the map also modify the returned set and vice versa.

Removing value from the set also removes the associated key/value pair from the Hashmap. There is no provision to do add operations on the returned set.

While iterating the returned set if you modify the underlying HashMap then the outcome of the iteration is unknown.

Use this method when you want to get the keys from the HashMap.

Method Signature

public Set<K> ketSet()


It does not accept any parameter.

Return value

 It returns the set of keys present in the HashMap


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

// This program shows
// how to use keySet() method
// to get the set of keys from the HashMap
public class HashMapKeySet {
	public static void main(String[] args) {

		// Create an instance of HashMap
		Map<Integer, String> map = new HashMap<>();

		// Add values to the map
		map.put(101, "John");
		map.put(102, "Adam");
		map.put(103, "Ricky");
		map.put(104, "Chris");

		// Entries present in the map
		System.out.println("Map elements : " + map);

		// Keys present in the map
		Set<Integer> keys = map.keySet();
		System.out.println("Keys in the map : " + keys);

		// Remove key from the set
		// This operation will also remove
		// associated entry from the HashMap

		System.out.println("After removing 101.");
		System.out.println("Keys in the map : " + keys);
		System.out.println("Map elements: " + map);


Map elements : {101=John, 102=Adam, 103=Ricky, 104=Chris}
Keys in the map : [101, 102, 103, 104]
After removing 101.
Keys in the map : [102, 103, 104]
Map elements: {102=Adam, 103=Ricky, 104=Chris}


  1. Create an instance of HashMap
  2. Add four elements to it
  3. At this point, the HashMap has four elements with keys 101, 102, 103, and 104
  4. Use the keySet() method to get the keys in HashMap
  5. You can remove elements from the returned set and the underlying HashMap will also remove the associated value.
  6. We removed key 101 and set the associated entry from the HashMap also got removed.
  7. If you are iterating the returned set and the HashMap is modified then the outcome of iteration cannot be predicted.
Categories: Java