How to iterate LinkedHashMap in Java?


LinkedHashMap is a class that is identical to HashMap, however it additionally provides a feature that tracks the order wherein components are inserted. The sequence wherein elements were added isn't preserved by using HashMap, even though it does permit for quick element insertion, search, and deletion.

By keeping a linked list of every entry in the map, LinkedHashMap addresses this issue. The elements are saved in the sequence that they were introduced thanks to this linked list. As a result, while iterating over a LinkedHashMap, the elements are returned according to how they were added.

Methods Used

To iterate LinkedHashMap in Java, you can use two main methods:

  • Employing the methods keySet() and get()

  • Making use of entrySet() and Iterator

Method 1: Employing The Methods keySet() and get()

The keySet() approach returns a set of all the keys within the map. The get() function returns the value related to a given key. With the aid of iterating over the keySet() and calling get() for each key, we can print all the key-value pairs inside the map.

Syntax

linked_hash_map.keySet()

There are no parameters needed for the LinkedHashMap class's keySet() function. It responds by returning a set that includes each key found in the LinkedHashMap.

This collection of keys may get iterated through to get the values that relate to the keys in the map using the get() method.

To time and again iterate over the map's keys, use a for loop. The for loop will repeat over the set returned by the keySet() method. For every iteration of the loop, the set's present key will be retrieved prior to using the get() method to obtain the map's linked value.

keySet()

This code makes use of the keySet() method to retrieve a set of keys from the LinkedHashMap and then iterates through each key using a for-every loop. Inside the loop, it makes use of the get() to retrieve the corresponding value for each key and prints the key-value pair.

Algorithm

  • Step 1 − First create an object. Here we have taken LinkedHashMap.

  • Step 2 − Create a few key-value pairs on the map.

  • Step 3 − Get the set of keys from the map using the keySet() function.

  • Step 4 − Iterate over the keys with the help of a for loop.

  • Step 5 − For every key, use the get() method to retrieve the value linked with that key.

  • Step 6 − Print the key and its corresponding value.

Example

// Iterate through LinkedHashMap with the help of keySet() and get() Method

import java.util.LinkedHashMap;
import java.util.Set;

public class Tutorialspoint {

   public static void main(String a[]){

      // creating the object of LinkedHashMap
      LinkedHashMap<String, String> linkedHashMap
      = new LinkedHashMap<String, String>();

      // addition of the elements in linkedHashMap
      linkedHashMap.put("P", "Python");
      linkedHashMap.put("J", "Java");
      linkedHashMap.put("R", "Ruby");

      Set<String> keys = linkedHashMap.keySet();

      // LinkedHashMap's elements are printed
      for (String key : keys) {
         System.out.println(key + " -- " + linkedHashMap.get(key));
      }
   }
}

Output

P -- Python
J -- Java
R -- Ruby

Method 2: Using entrySet() and Iterator

Iterating over a LinkedHashMap using the entrySet() approach and an Iterator lets in you to traverse via the factors of the map in a selected order, keeping the insertion order.

Syntax

Linkedhash_map.entrySet()

Parameters − The technique does not take any input parameters.

Return value: The approach returns a set that incorporates the identical elements as the LinkedHashMap.

In other words, the procedure can be used without the user providing any data. It merely gives back a set containing a copy of the LinkedHashMap's contents.

entrySet()

The code example explains how you may iterate over a LinkedHashMap. It prints its entries. It makes use of the entrySet() function to retrieve a set of key-value pairs. It then creates an iterator to traverse through the entries and prints each entry separately. The output shows us the entries of the LinkedHashMap with the keys and their corresponding values.

Algorithm

  • Step 1 − Create a LinkedHashMap object named "linkedHashMap".

  • Step 2 − Add elements to the linkedHashMap using the put() method.

  • Step 3 − Obtain the entry set from the linkedHashMap using the entrySet() method and store it in the "entrySet" variable.

  • Step 4 − Create an iterator using the iterator() method on the entrySet.

  • Step 5 − Iterate through the LinkedHashMap entries using a while loop.

  • Step 6 − In the loop, take a look at if the iterator with the usage of the hasNext() method.

  • Step 7 − If there are more entries, then retrieve the next entry using the next() method.

  • Step 8 − Print the output.

Example

// Iterating over linkedHashMap by employing entrySet() and iterator

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

public class TLP {

   public static void main(String[] args){

      // Create a LinkedHashMap and add elements to it
      LinkedHashMap<String, String> linkedHashMap
      = new LinkedHashMap<String, String>();

      // incorporating the elements to the linkedHashMap
      linkedHashMap.put("Java", "is the first elemenent");
      linkedHashMap.put("Python", "is the second element");
      linkedHashMap.put("Ruby", "is the third element");

      Set entrySet = linkedHashMap.entrySet();

      // Obtain an Iterator for the entries Set
      Iterator it = entrySet.iterator();

      // Iterate through LinkedHashMap entries
      System.out.println("LinkedHashMap entries -> ");

      while (it.hasNext())
      // iterating over each element employing it.next()
      System.out.println(it.next());
   }
}

Output

LinkedHashMap entries -> 
Java=is the first elemenent
Python=is the second element
Ruby=is the third element

Conclusion

Iterating over a LinkedHashMap in Java may be done the usage of two essential techniques −

Through using the keySet() approach and get() technique, wherein you retrieve a fixed of keys from the map and iterate over them to access the corresponding values.

By means of the usage of the entrySet() approach and an Iterator, which allows you to traverse via the factors of the map inside the order of insertion.

Updated on: 19-Oct-2023

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements