What is the LinkedHashMap.keySet method in Java?

In a LinkedHashMap, we can use the keySet method to get all the keys of the LinkedHashMap object as a Set collection.

Any changes then made to the associated set are reflected in the map as well, and vice versa. The set allows elements to be removed, and those keys that are removed from the set are also removed from the map.

A LinkedHashMap is the same as a HashMap, except that the LinkedHashMap maintains the insertion order, whereas the HashMap does not. Internally, the LinkedHashMap uses the doubly-linked list to maintain the insertion order. Read more about LinkedHashMap here.

Syntax

public Set<K> keySet()

Parameters

This method doesn’t take any arguments.

Return value

The keySet method will return a set viewIt returns a class object that implements the set interface, which operates on the original mapping. of all keys in the map.

Code

The example below shows how to use the keySet method.

import java.util.LinkedHashMap;
import java.util.Set;
class LinkedHashMapKeySetExample {
public static void main( String args[] ) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "one");
map.put(2, "two");
System.out.println("The map is -" + map );
Set<Integer> keys = map.keySet();
System.out.println("The keys are -" + keys );
System.out.println("\nAdding a new entry 4 - four to the map" );
map.put(4, "four");
System.out.println("After adding the keys, map keys are -" + keys );
System.out.println("\nDelting the entry 1 from the set" );
map.remove(1);
System.out.println("After deleting the keys, map keys are -" + keys );
}
}

Explanation

In the code above:

  • In line 1, we import the LinkedHashMap class.

  • In line 6, we create a LinkedHashMap object with the name map.

  • In lines 7 and 8, we use the put method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 12, we get the keys of the LinkedHashMap using the keySet method and store them in the keys variable.

  • In line 16, we add a new entry (4,"four") to the map.

  • In line 17, we print the keys. For the newly added entry, the key - 4 is automatically available in the keys variable without the need to call the keySet method.

  • In line 20, we delete the 1 - "one" entry of the map. The deleted entry’s key will not be present in the keys variable.

Free Resources