![]() |
VOOZH | about |
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.
Methods:
Illustration:
Input :
Key- 2 : Value-5
Key- 14 : Value-35
Key- 31 : Value-20
Key- 36 : Value-18
Key- 52 : Value-6
Output:
Key Value
First-> 2 5
Last -> 52 6
Method 1: Naive approach using the for-each loop for iteration over Map.
Construct function getFirst() and getLast()
Example:
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.
Algorithm:
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.
Example:
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.
Algorithm
Pseudo Code: List<Integer> lKeys = new ArrayList<Integer>(LHM.keySet()); // where LHM is name of LinkedHashMap and lKeys is name of List
Example
First key: 1 First value: 8 Last key: 5 Last value: 5
Time Complexity: O(1)