How to Get a Value from LinkedHashMap by Index in Java

Introduction

One of the most crucial data structures to learn while preparing for interviews is the linked list. In a coding interview, having a thorough understanding of Linked Lists might be a major benefit.

LinkedHashMap is a Java predefined class that is similar to HashMap, which contains keys and their respective values. The order of insertion in LinkedHashMap is preserved.

Our objective here is to get a value from the LinkedHashMap by index. We can use many approaches to solve this problem. Let us have a look at the different approaches.

Approach and Algorithm 1

In this approach, we will convert all the LinkedHashMap keys to a set with the help of keySet() function and then will convert this newly created set to an array with the help of the toArray() function.

As of now, we have an array; we can get a value by index.

Syntax: Object [ ] toArray ( )

Parameters: This function does not take any parameters.

Return Value: The function returns a new array that contains the elements of the set.

Input

[ [1,2] , [3,4] , [5,6] ], Index of the element to be fetched - 2

Output

Value at index 2 is 4

Explanation: As we can see, at the 2nd index, the key-value pair is [ 3, 4 ], so our output will be 4, the value at the 2nd index.

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

        Set keySet = LinkedHMap.keySet();
  
        Integer[] keyArray
            = keySet.toArray(new Integer[keySet.size()]);
  
        Integer index = 2;
        Integer key = keyArray[index - 1];

        System.out.println("Value at index " + index
                           + " is: " + LinkedHMap.get(key));
    }
}
Output

Value at index 2 is: 4

Time Complexity: The time complexity is O(N), as we are walking over the keyset to convert it to the array.

Space Complexity: The space complexity is O(N), as we are creating an array of N size.

Approach and Algorithm 2

In this approach, we will first convert the keys of the LinkedHashMap to a set using the LinkedHashMap.keySet() method and then will convert this newly created set to ArrayList using new ArrayList(keySet).

This method converts all the keys to a list-like structure - ArrayList or LinkedList.

Input

[ [1,2] , [3,4] , [5,6] ], Index of the element to be fetched - 2

Output

Value at index 2 is 4

Explanation: As we can see, at the 2nd index, the key-value pair is [ 3, 4 ], so our output will be 4, the value at the 2nd index.

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

        Set keySet = LinkedHMap.keySet();

        List listKeys
            = new ArrayList(keySet);
  
        Integer index = 2; 
        Integer key = listKeys.get(index - 1);

        System.out.println("Value at index " + index
                           + " is: " + LinkedHMap.get(key));
    }
}

Output

Value at index 2 is: 4

Time Complexity: The time complexity is O(N), as we are walking over the KeySet to convert it to a list.

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

Approach and Algorithm 3

In this approach, we will use Iterators. With the help of entrySet(), we can get all the entries of the LinkedHashMap. After this, we will iterate till the specified index and print the value at that index.

Input

[ [1,2] , [3,4] , [5,6] ], Index of the element to be fetched - 2

Output

Value at index 2 is 4

Explanation: As we can see, at the 2nd index, the key-value pair is [ 3, 4 ], so our output will be 4, the value at the 2nd index.

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


        Set > entrySet
            = LinkedHMap.entrySet();

        Iterator > iterator
            = entrySet.iterator();
  
        int i = 0;
        int index = 2;
        int value = 0;
  
        while (iterator.hasNext()) {
  
            if (index - 1 == i) {
                value = iterator.next()
                            .getValue(); 
                break;
            }
  
            iterator.next();
            i++;
        }

        System.out.println("Value at index " + index + " is: "
                           + value);
    }
}

Output

Value at index 2 is: 4

Time Complexity: The time complexity is O(N), as we are traversing till the specified index.

So, in this article, we have seen how to get a value from LinkedHashMap by Index in Java. Java Collection Framework is very important when it comes to coding interviews. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.

Previous post Delete all occurrences of a given key in a doubly linked list
Next post How To Write C Functions That Modify The Head Pointer Of A Linked List

Leave a Reply

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