Retrieving Value from a LinkedHashMap by Index in Java

dhruv sharma
Last Updated: May 13, 2022

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. 
 

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

linkedhashmap.put(73);

linkedhashmap.put(29);

linkedhashmap.put(61);

linkedhashmap.put(511);

 

// 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.

 

Method 2 (Using a list to retrieve values by index) 

 

Approach: This method uses a similar process of retrieving a set of keys from 'LinkedHashMap' but adds the elements to a 'LinkedList' or 'ArrayList' instead of an array.

Syntax: new ArrayList, new LinkedList

Parameter: ‘Object<Object>()’

Return value: object of a ‘List’ class.

 

Example of this method with the help of a program
 

Code
 

// Method 2: get a value from LinkedHashMap by index using //ArrayList/LinkedList

 

import java.util.*;

import java.io.*;

 

public class CodingNinjas {

 

public static void main(String[] args)

{

 

// create an instance of linked hash map

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

 

// Add mappings

linkedhashmap.put(35);

linkedhashmap.put(73);

linkedhashmap.put(29);

linkedhashmap.put(61);

linkedhashmap.put(511);

 

// get the key set

Set<Integer> keyset = linkedhashmap.keySet();

/*

Integer[] keyArray = keySet.toArray(new

Integer[keySet.size()]); replacing array with

ArrayList here.

*/

List<Integer> listkeys = new ArrayList<Integer>(keySet);

 

Integer index = 3// taking input of index

Integer key = listkeys.get(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 ArrayList/LinkedList to store the outputs of the set values.

 

Method 3 (Using an entrySet and Iterator to retrieve values by index) 

 

Approach: This method uses an Iterator reference for the entrySet type object obtained from our 'LinkedHashMap' of values in the map that we have.

Syntax: Set<map.entry<Object, Object>>()

Parameter: Set<Object>()

Return value: it will return a Set of map.entry<Object, Object> object.

Example of this method with the help of a program.

 

Code

import java.util.*;

import java.io.*;

  

public class CodingNinjas {

    public static void main(String[] args)

    {

 

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

 

        // Add mappings

        linkedhashmap.put(35);

        linkedhashmap.put(73);

        linkedhashmap.put(29);

        linkedhashmap.put(61);

        linkedhashmap.put(511);

 

        Set<map.entry<Integer, Integer> > entryset = linkedhashmap.entrySet();

 

        Iterator<map.entry<Integer, Integer> > iterator = entryset.iterator();

  

        int i = 0;

        int index = 3;

        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 3 is : 9

 

Time Complexity: O(N), since we are converting all keys present in the 'LinkedHashMap' using the 'entrySet' method, which has a worst-case time complexity of O(N).

Space Complexity: O(N), since we are using a Set of map.entry to store the outputs of the set values.

 

FAQ’s

 

1. What do you mean by LinkedList data structure?

LinkedList is a linear data structure where elements are connected through links in non-contiguous locations. Each element is known as a node. There are three types of LinkedList known as Singly LinkedList, Doubly LinkedList, and Circular LinkedList.

 

2. What is the advantage of using the last method over others?

The last way of traversing the values and retrieving them using an entrySet and an iterator would also return correct values even when duplicate values are in the 'LinkedHashMap'.

 

Key Takeaways

 

In this blog, we learned about the various methods of getting values from 'LinkedHashMap' by index in Java that helps us to retrieve a specified value at the specified position. We understood their syntaxes and functions with the help of examples.

 

You can also have a view of the Data Structures and Algorithms-guided path to start your preparation from scratch.

 

Happy Coding!!!
 

Was this article helpful ?
0 upvotes