How to Get First or Last Entry from Java LinkedHashMap?
LinkedHashMap is a predefined class in Java which is similar to HashMap, containing key and its respective value unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to get the first and last entry present in LinkedHashMap. Iteration to get last and first value. The first and the last entry in Map is the entry that is inserted first and the entry that is to be inserted last where insertion order is preserved.
- The naive approach using the for-each loop for iteration over Map.
- Converting the keys of LinkedHashMap to an integer array.
- Converting keys in LinkedHashMap to List like ArrayList to LinkedList.
Key- 2 : Value-5
Key- 14 : Value-35
Key- 31 : Value-20
Key- 36 : Value-18
Key- 52 : Value-6
First-> 2 5
Last -> 52 6
Method 1: Naive approach using the for-each loop for iteration over Map.
Construct function getFirst() and getLast()
- getFirst() print the first entry
- getLast() move to last entry (index is equal to size of LinkedHashMap)
First Key-> 2 First Value-> 5 Last Key-> 52 Last Value-> 6
Time complexity: O(n)
Method 2: Converting the keys of LinkedHashMap to an integer array.
- Getting first and value corresponding to the key.
- Printing last and value corresponding to the key.
Pseudo Code : Integer aKeys = LHM.keySet().toArray(new Integer[LHM.size()]); // where LHM is name of LinkedHashMap created and aKeys of array to be converted.
First key-> 1 First value-> 8 Last key-> 5 Last value-> 5
Time Complexity: O(1)
Method 3: Converting keys in LinkedHashMap to List like ArrayList to LinkedList.
- Get first and the value corresponding to the key.
- Print last and the value corresponding to the key.
Pseudo Code: List<Integer> lKeys = new ArrayList<Integer>(LHM.keySet()); // where LHM is name of LinkedHashMap and lKeys is name of List
First key: 1 First value: 8 Last key: 5 Last value: 5
Time Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.