Home » Core Java » util » LinkedHashMap » LinkedHashMap Iterator example

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

LinkedHashMap Iterator example

In this example we shall show you how to obtain a LinkedHashMap Iterator, that is an iterator over the LinkedHashMap key value pairs. To obtain a LinkedHashMap Iterator one should perform the following steps:

  • Create a new LinkedHashMap.
  • Populate the linkedHashMap with elements, with put(K key, V value) API method of LinkedHashMap.
  • Invoke entrySet() API method of LinkedHashMap. It returns a Set with the key- value pairs that the linkedHashMap contains.
  • Invoke iterator() API method of Set, to obtain the Set iterator.
  • Iterate through the linkedHashMap entries, with hasNext() anf next() API methods of Iterator,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
 
public class LinkedHashMapIterator {
 
  public static void main(String[] args) {
 

// Create a LinkedHashMap and populate it with elements

LinkedHashMap linkedHashMap = new LinkedHashMap();

linkedHashMap.put("key_1","value_1");

linkedHashMap.put("key_2","value_2");

linkedHashMap.put("key_3","value_3");


// Get a set of all the entries (key - value pairs) contained in the LinkesHashMap

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

  System.out.println(it.next());
    
  }
}

Output:

LinkedHashMap entries : 
key_1=value_1
key_2=value_2
key_3=value_3

 
This was an example of how to obtain a LinkedHashMap Iterator in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments