What is the LinkedHashMap.entrySet method in Java?
A LinkedHashMap is the same as a regular HashMap, except that a LinkedHashMap maintains the insertion order, whereas a HashMap does not.
Internally, the LinkedHashMap uses a doubly-linked list to maintain the insertion order.
The entrySet method
In a LinkedHashMap, we can use the entrySet method to get all the LinkedHashMap object as a set view.
Syntax
public Set<Map.Entry<K,V>> entrySet()
Parameters
This method doesn’t take any parameters.
Return value
The entrySet method returns a set view of all of the entries in the map.
Code
The example below shows how to use the entrySet method.
import java.util.LinkedHashMap;import java.util.Set;import java.util.Map;class EntrySetExample {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<Map.Entry<Integer, String>> entries = map.entrySet();System.out.println("The entries are -" + entries);System.out.println("\nAdding a new entry 4 - four to the map" );map.put(4, "four");System.out.println("After adding the entries are -" + entries);}}
Explanation
In the code above:
-
In line 1, we import the
LinkedHashMapclass. -
In line 7, we create a
LinkedHashMapobject with the namemap. -
In lines 8 and 9, we use the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 13, we get the entries of the
LinkedHashMapwith theentrySetmethod and store them in theentriesvariable. -
In line 17, we add a new entry
4 - "four"to themap. -
In line 19, we print
entries. The newly added entry,4 - "four", will automatically be available in theentriesvariable without the need to call theentrySetmethod because theentrySetmethod returns the set view.