VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-get-first-or-last-entry-from-java-linkedhashmap/

⇱ How to Get First or Last Entry from Java LinkedHashMap? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Get First or Last Entry from Java LinkedHashMap?

Last Updated : 9 Jun, 2021

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:

  1. The naive approach using the for-each loop for iteration over Map. 
  2. Converting the keys of LinkedHashMap to an integer array.
  3. Converting keys in LinkedHashMap to List like ArrayList to LinkedList.

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()

  • getFirst() print the first entry
  • getLast() move to last entry (index is equal to size of LinkedHashMap)

Example:


Output
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: 

  • 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.

Example: 


Output
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 

  • 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

Example 


Output
First key: 1
First value: 8
Last key: 5
Last value: 5


Time Complexity: O(1)


 

Comment