
Introduction
We will discuss the Java ‘LinkedHashMap’ class and its functions, making our jobs easier while writing code. LinkedList and HashMap are crucial data structures that one should be well versed in for interview rounds.
The ‘LinkedHashMap' class in the Java collections package provides a hashmap data structure that provides an easy storage interface for adding and retrieving key-value pairs in sequential order, unlike the conventional 'HashMap' interface in Java. Elements in 'LinkedHashMap' are connected through links in a scattered(not sequential) manner. 'LinkedHashMap' offers various methods that allow us to perform different operations such that its insertion orders are preserved.
In this article, we will look at a few ways through which we would be able to get the values from a 'LinkedHashMap' by index.
Recommended Topic, Floyds Algorithm And Rabin Karp Algorithm
Method 1 (Using an array to retrieve values by index)
Approach: Here, we try to use the 'keySet' method to retrieve all the values in the form of the 'Set' class in Java that is present in the 'LinkedHashMap' corresponding to the keys that were inserted in it and then convert the retrieved set of values to an array after which It can easily access the value required to be retrieved by a given index from the array.
Syntax: Object [] toArray()
Parameter: the following method that is utilised here doesn’t require any parameters
Returned value: it will return a set of all the values present in the 'LinkedHashMap'.
Example of this method with the help of a program
Code
// Method 1: get a value from LinkedHashMap by index using Array
import java.util.*;
import java.io.*;
public class CodingNinjas {
public static void main(String[] args)
{
// create a linked hash map instance
LinkedHashMap<Integer, Integer> linkedhashmap = new LinkedHashMap<Integer, Integer>();
// Add mappings
linkedhashmap.put(3, 5);
linkedhashmap.put(7, 3);
linkedhashmap.put(2, 9);
linkedhashmap.put(6, 1);
linkedhashmap.put(5, 11);
// get the key set
Set<Integer> keyset = linkedhashmap.keySet();
Integer[] keyarray = keyset.toArray(new Integer[keyset.size()]);
// taking input of index
Integer index = 3;
Integer key = keyarray[index - 1];
// get value from the LinkedHashMap for the key
System.out.println("Value at index " + index + " is : " + linkedhashmap.get(key));
}
}
Output
| Value at index 3 is : 9 |
Time Complexity: O(N), since we are converting all keys present in the 'LinkedHashMap' using the 'keySet' method, which has a worst-case time complexity of O(N).
Space Complexity: O(N), since we are using arrays to store the outputs of the set values.
Read More - Time Complexity of Sorting Algorithms






