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 a Value from LinkedHashMap by Index in Java

Last Updated on December 13, 2022 by Prepbytes

Basically, If we will use linkedhashmap class we can retrieve or fetch the value which is mapped through a parameter which contains a key. So lets just look into a program on how to get value from linkedhashmap in java

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 on how to get value from linkedhashmap in java

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 on how to get value from linkedhashmap in java


import java.util.*;
import java.io.*;
  
public class PrepBytes {
  
    public static void main(String[] args)
    {

        LinkedHashMap<integer, integer=""> LinkedHMap
            = new LinkedHashMap<integer, integer="">();

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

        Set<integer> 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 on how to get value from linkedhashmap in java

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 on how to get value from linkedhashmap in java

import java.util.*;
import java.io.*;
  
public class PrepBytes {
  
    public static void main(String[] args)
    {

        LinkedHashMap<Integer, Integer> LinkedHMap
            = new LinkedHashMap<Integer, Integer>();

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

        Set<Integer> keySet = LinkedHMap.keySet();

        List<Integer> listKeys
            = new ArrayList<Integer>(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 on how to get value from linkedhashmap in java

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 on how to get value from linkedhashmap in java

import java.util.*;
import java.io.*;
  
public class PrepBytes {
    public static void main(String[] args)
    {

        LinkedHashMap<Integer, Integer> LinkedHMap
            = new LinkedHashMap<Integer, Integer>();

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


        Set<Map.Entry<Integer, Integer> > entrySet
            = LinkedHMap.entrySet();

        Iterator<Map.Entry<Integer, Integer> > 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.

Conclusion

So, in the above article we tried to understand how to get the value from linkedhashmap in java. We have also learnt how to use a parameter and key in it to do mapping. The hashmap returns the value null when there is no such key mapping. 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.

Related Articles
Doubly circular linked list in data structure Application of doubly linked list
Applications of linked list Singly linked list vs doubly linked list
Advantages and disadvantages of linked list Doubly linked list all operations in C
Binary search in linked list Bubble sort linked list
Deletion in doubly linked list Delete the middle node of a linked list
Polynomial addition using linked list Find max value and min value in linked list
Insert a node at a specific position in a linked list Swap nodes in linked list
Add two numbers represented by linked lists Find starting point of loop in linked list
Merge sort linked list Delete a node from linked list at a given position
Remove duplicates from unsorted linked list Reverse a linked list in Python

FAQs

  1. In the linked hash map does the order is preserved?

  2. The Linkedhash map is a predefined class in java which preserves the order of insertion.

  3. How to update the value in linked hashmap?

  4. To update the value in linkedhashmap we can use replace method to replace the value through a parameter and the key in it by mapping.

  5. Is linked hashmap thread-safe?

  6. In Linkedhashmap we should synchronize the concurrent access to a multithreaded environment explicitly. So, linkedhashmap is not thread safe.

Leave a Reply

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