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
LinkedHashMapis the same as aHashMap, except that theLinkedHashMapmaintains the insertion order, whereas theHashMapdoes not. Internally, theLinkedHashMapuses the doubly-linked list to maintain the insertion order. Read more aboutLinkedHashMaphere.
Syntax
public Set<K> keySet()
Parameters
This method doesn’t take any arguments.
Return value
The keySet method will return a
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
LinkedHashMapclass. -
In line 6, we create a
LinkedHashMapobject with the namemap. -
In lines 7 and 8, we use the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 12, we get the keys of the
LinkedHashMapusing thekeySetmethod and store them in thekeysvariable. -
In line 16, we add a new entry
(4,"four")to themap. -
In line 17, we print the
keys. For the newly added entry, thekey - 4is automatically available in thekeysvariable without the need to call thekeySetmethod. -
In line 20, we delete the
1 - "one"entry of themap. The deleted entry’skeywill not be present in thekeysvariable.