Open In App

How to Get First or Last Entry from Java LinkedHashMap?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

Java




// Java Program to get first or last entry
// from Java LinkedHashMap
 
// Importing all class of
// java.util package
import java.util.*;
// Importing java input/output classes
import java.io.*;
 
class GFG {
 
  // getLast() method
    public static void
    getLast(LinkedHashMap<Integer, Integer> lhm)
    {
        int count = 1;
 
        for (Map.Entry<Integer, Integer> it :
             lhm.entrySet()) {
           
            if (count == lhm.size()) {
               
                System.out.println("Last Key-> "+it.getKey());
              System.out.println("Last Value-> "+it.getValue());
                return;
            }
            count++;
        }
    }
 
  // getFirst() method to get first element from
  // java LinkedHashMap
    public static void
    getFirst(LinkedHashMap<Integer, Integer> lhm)
    {
        int count = 1;
 
        for (Map.Entry<Integer, Integer> it :
             lhm.entrySet()) {
            if (count == 1) {
              System.out.println("First Key-> "+it.getKey());
              System.out.println("First Value-> "+it.getValue());
                return;
            }
            count++;
        }
    }
 
  // Main driver method
    public static void main(String[] args)
    {
 
      // Creating(defining) a LinkedHashMap
        LinkedHashMap<Integer, Integer> LHM
            = new LinkedHashMap<>();
 
      // Adding elements to above LinkedHashMap
        LHM.put(2, 5);
        LHM.put(14, 35);
        LHM.put(36, 20);
        LHM.put(34, 18);
        LHM.put(52, 6);
       
      // Calling getFirst() method in main()
        getFirst(LHM);
       
      // Calling getLast() method in main()
        getLast(LHM);
    }
}


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: 

Java




// Java Program to get first or last entry
// from Java LinkedHashMap
// By converting Map to integer array
 
// Importing all class of
// java.util package
import java.util.*;
// Importing java input/output classes
import java.io.*;
 
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a LinkedHashMAp
        LinkedHashMap<Integer, Integer> LHM
            = new LinkedHashMap<>();
 
        // Adding. elements to above LinkedHashMap
        // Custom inputs
        LHM.put(1, 8);
        LHM.put(2, 6);
        LHM.put(3, 7);
        LHM.put(4, 2);
        LHM.put(5, 5);
 
        // Getting all keys from the LinkedHashMap, and
        // converting it to an array
        Integer[] aKeys
            = LHM.keySet().toArray(new Integer[LHM.size()]);
 
        // Condition check
        // If array is having element
        // Print key and value
        if (aKeys.length > 0) {
 
            // Print first key and first value
            // From integer array
            System.out.println("First key-> " + aKeys[0]);
            System.out.println("First value-> "
                               + LHM.get(aKeys[0]));
 
            // Print first key from integer array
            System.out.println("Last key-> "
                               + aKeys[aKeys.length - 1]);
 
            // Print last value from integer array
            System.out.println(
                "Last value-> "
                + LHM.get(aKeys[aKeys.length - 1]));
        }
    }
}


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 

Java




// Java Program to get first or last entry
// from Java LinkedHashMap
// By converting Map to List
 
// Importing all class of
// java.util package
import java.util.*;
// Importing java input/output classes
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating a LinkedHashMapc
        LinkedHashMap<Integer, Integer> LHM
            = new LinkedHashMap<>();
 
        // Adding elements to above LinkedHashMap
        // Custom inputs
        LHM.put(1, 8);
        LHM.put(2, 6);
        LHM.put(3, 7);
        LHM.put(4, 2);
        LHM.put(5, 5);
 
        // Creating a List
        List<Integer> lKeys
            = new ArrayList<Integer>(LHM.keySet());
 
        // Condition check
        // If there is single element in List
        // Print key and value
        if (lKeys.size() > 0) {
 
            // Print first key form List
            System.out.println("First key: "
                               + lKeys.get(0));
 
            // Print first value from List
            System.out.println("First value: "
                               + LHM.get(lKeys.get(0)));
 
            // Print last key from List
            System.out.println(
                "Last key: " + lKeys.get(lKeys.size() - 1));
 
            // Print last value from List
            System.out.println(
                "Last value: "
                + LHM.get(lKeys.get(lKeys.size() - 1)));
        }
    }
}


Output

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

Time Complexity: O(1)

 



Last Updated : 09 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads