Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

How to Get First or Last entry from Java LinkedHashMap

Last Updated on July 24, 2023 by Mayank Dham


In Java, the LinkedHashMap class offers a unique advantage over other map implementations by maintaining the insertion order of its elements. This means that elements are stored in the order in which they were added to the map, making it a valuable data structure in scenarios where element order matters. One common requirement in programming is to retrieve the first or last element from a LinkedHashMap using linkedhashmap get first Element and LinkedHashMap Get Last element, based on the insertion order. In this article, we will explore how to efficiently obtain the first and last elements from a LinkedHashMap using linkedhashmap get first Element and LinkedHashMap Get Last element in Java. We will delve into the underlying mechanisms of LinkedHashMap that enable it to maintain insertion order and discuss the various methods and approaches that can be employed to retrieve elements from both ends of the map. Additionally, we will analyze the time and space complexities of these operations to understand their efficiency in different use cases.

How to retrieve the First and last entries in LinkedHashMap?

The objective is to retrieve the first and last entries in the LinkedHashMap. The last and first values are obtained by iteration. The first and last entries in LinkedHashMap are the first and last entries that are inserted in the LinkedHashMap, as the insertion order is retained. We can achieve this by using different approaches and algorithms.

Approach and Algorithm 1

This is going to be a Naive approach. We are going to use the for-each loop to iterate over the LinkedHashMap.

We will construct two functions:

getFirst()

  • This function will print the first entry of the LinkedHashMap.
  • We will traverse the LinkedHashMap and maintain a counter, which will initially be 1 and will be incremented by 1 in every iteration.
  • During the traversal, when the counter will be equal to 1, we will print the values, as counter = 1 means that we are standing at the first element.

getLast()

  • This function will print the last entry of the LinkedHashMaop.
  • We will traverse the LinkedHashMap and maintain a counter, which will initially be 1 and will be incremented by 1 in every iteration.
  • During the traversal, when the counter will be equal to the size of the LinkedHashMap, we will print the values, as counter = LinkedHashMap.size() means that we are standing at the last element.
Sample Input

[ [1,2] , [3,4] , [5,6] ]

Sample Output

First Key = 1 , First Value = 2
Last Key = 5 , Second Value = 6

Explanation: As we can see, the first and last key-value pairs have been printed.

Code Implementation

import java.util.*;

import java.io.*;
 
public class PrepBytes {
    // Get the last entry of the map
    public static void
    getLast(LinkedHashMap LinkedHMap)
    {
        int count = 1;
 
        for (Map.Entry it :
             LinkedHMap.entrySet()) {
           
            if (count == LinkedHMap.size()) {
               
                System.out.println("Last Key-> "+it.getKey());
              System.out.println("Last Value-> "+it.getValue());
                return;
            }
            count++;
        }
    }
    // Get the First entry of the map
    public static void
    getFirst(LinkedHashMap LinkedHMap)
    {
        int count = 1;
 
        for (Map.Entry it :
             LinkedHMap.entrySet()) {
            if (count == 1) {
              System.out.println("First Key-> "+it.getKey());
              System.out.println("First Value-> "+it.getValue());
                return;
            }
            count++;
        }
    }

    public static void main(String[] args)
    {
 
        LinkedHashMap LinkedHMap
            = new LinkedHashMap<>();

        LinkedHMap.put(1, 2);
        LinkedHMap.put(3,4);
        LinkedHMap.put(5, 6);

       

        getFirst(LinkedHMap);
       
        getLast(LinkedHMap);
    }
}

Output

First Key-> 1
First Value-> 2
Last Key-> 5
Last Value-> 6

Time Complexity:

  • Getfirst() – O(1), as we only need the first element of the LinkedHashMap
  • Getlast() – O(n), as LinkedHashMap traversal is needed.

Space Complexity:
For both the methods, the space complexity is O(1), as no extra space is being used.

Approach 2: Converting Keys of LinkedHashMap to an Array

  • In this approach, we will convert the keys of the LinkedHashMap to an array, with the help LinkedHashMap.keySet().toArray( new Integer[ LinkedHashMap.size()] ) method. This method converts the keys of the LinkedHashMap into an array.
  • After converting, we will simply print the key-value pair at the 0-th index, as it will be our first element and print the key-value pair at the keys.length-1 th index as it will be the last key-value pair.
Sample Input

[ [1,2] , [3,4] , [5,6] ]

Sample Output

First Key = 1 , First Value = 2
Last Key = 5 , Second Value = 6

Explanation: As we can see, the first and last key-value pairs have been printed.

Code Implementation

import java.util.*;

import java.io.*;
 
public class PrepBytes {

    public static void main(String[] args)
    {

        LinkedHashMap LinkedHMap
            = new LinkedHashMap<>();

        LinkedHMap.put(1, 2);
        LinkedHMap.put(3, 4);
        LinkedHMap.put(5, 6);


        Integer[] keys
            = LinkedHMap.keySet().toArray(new Integer[LinkedHMap.size()]);

        if (keys.length > 0) {

            System.out.println("First key-> " + keys[0]);
            System.out.println("First value-> "
                               + LinkedHMap.get(keys[0]));

            System.out.println("Last key-> "
                               + keys[keys.length - 1]);
 
            System.out.println(
                "Last value-> "
                + LinkedHMap.get(keys[keys.length - 1]));
        }
    }
}

Output

First Key-> 1
First Value-> 2
Last Key-> 5
Last Value-> 6

Time Complexity: For both methods, the time complexity is O(1), as we are accessing the elements with the help of indexes.

Space Complexity: For both methods, the space complexity is O(N), as we are creating an array that consists of N keys.

Approach 3 : Using LinkedHashMap.keySet()

In this approach, we will convert the keys of the LinkedHashMap to an array with the help of LinkedHashMap.keySet() method. This method converts all the keys to a list like structure – ArrayList or LinkedList.After converting, we will simply print the key-value pair at the 0-th index, as it will be our first element and print the key-value pair at the LinkedHashMap.size() -1 index as it will be the last key-value pair.

Sample Input

[ [1,2] , [3,4] , [5,6] ]

Sample Output

First Key = 1, First Value = 2
Last Key = 5, Second Value = 6

Explanation: As we can see, the first and last key-value pairs have been printed.

Code Implementation

import java.util.*;

import java.io.*;

public class PrepBytes {

    public static void main(String[] args)
    {

        LinkedHashMap LinkedHMap
            = new LinkedHashMap<>();

        LinkedHMap.put(1, 2);
        LinkedHMap.put(3, 4);
        LinkedHMap.put(5, 6);
  

        List lKeys
            = new ArrayList(LinkedHMap.keySet());

        if (lKeys.size() > 0) {

            System.out.println("First key-> "
                               + lKeys.get(0));

            System.out.println("First value-> "
                               + LinkedHMap.get(lKeys.get(0)));

            System.out.println(
                "Last key-> " + lKeys.get(lKeys.size() - 1));

            System.out.println(
                "Last value-> "
                + LinkedHMap.get(lKeys.get(lKeys.size() - 1)));
        }
    }
}

Output

First Key-> 1
First Value-> 2
Last Key-> 5
Last Value-> 6

Time Complexity: For both methods, the time complexity is O(1), as we are accessing the elements with the help of indexes.

Space Complexity: For both methods, the space complexity is O(N), as we are creating a list-like structure that consists of N keys.

Conclusion
In this article, we explored different approaches to obtaining the first and last elements from a LinkedHashMap in Java. By leveraging the insertion order maintenance of LinkedHashMap, we efficiently obtained the elements from both ends of the map using methods like Linkedhashmap get first element and LinkedHashMap Get Last element. We discussed three different approaches: the Naive Approach using iteration, converting keys to an array, and using LinkedHashMap.keySet() to achieve the desired results. Each approach had its own time and space complexity considerations, which we analyzed to understand their efficiency in various scenarios. By following the presented methods, Java developers can easily access the first and last elements of a LinkedHashMap based on the insertion order, allowing for more efficient data manipulation and processing in their applications.

Frequently Asked Questions (FAQs)

Here are some of the most frequently asked questions on LinkedHashMap in Java

Q1. Can we use other map implementations, such as HashMap or TreeMap, to retrieve the first and last elements, like LinkedHashMap?
No, HashMap and TreeMap do not guarantee the maintenance of insertion order like LinkedHashMap does. Therefore, using these implementations may not yield accurate results when trying to retrieve the first and last elements based on the order of insertion.

Q2. Is there any difference in performance between the three approaches discussed in the article to obtain the first and last elements from a LinkedHashMap?
Yes, there is a difference in performance. The first approach, which uses iteration, has a time complexity of O(n) since it traverses the entire LinkedHashMap. The second and third approaches, which convert keys to an array or list-like structure, have a time complexity of O(1) as they directly access the elements using indexes.

Q3. Can I use the same approaches discussed in the article for retrieving elements from a LinkedHashMap with custom objects as keys?
Yes, you can use the same approaches for custom objects as keys, provided that the custom objects have proper implementations of the hashCode() and equals() methods to maintain the correct ordering in the LinkedHashMap.

Q4. Does the LinkedHashMap guarantee that the first element inserted will always be the first element retrieved using the discussed methods?
Yes, LinkedHashMap ensures that the first element inserted will be the first element retrieved when using the discussed methods, as it maintains the insertion order of its elements.

Q5. Can we use LinkedHashMap to maintain a sorted order of elements instead of insertion order?
No, LinkedHashMap is specifically designed to maintain the insertion order of elements, not a sorted order. If you require sorted elements, consider using TreeMap, which sorts the elements based on their natural ordering, or a custom comparator.

Leave a Reply

Your email address will not be published. Required fields are marked *