Iterate through the values of Java LinkedHashMap in Java

Java 8Object Oriented ProgrammingProgramming

An iterator is used in Java to iterate through the values of LinkedHashMap.

Let us first create LinkedHashMap −

LinkedHashMap<String,String> l = new LinkedHashMap<String,String>();

Add some elements to the LinkedHashMap −

l.put("1", "Jack");
l.put("2", "Tom");
l.put("3", "Jimmy");
l.put("4", "Morgan");
l.put("5", "Tim");
l.put("6", "Brad");

Iterate through the values −

Collection res = l.values();
Iterator i = res.iterator();
while (i.hasNext()){
   System.out.println(i.next());
}

The following is an example to iterate through the values of LinkedHashMap −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      LinkedHashMap<String,String> l = new LinkedHashMap<String,String>();
      l.put("1", "Jack");
      l.put("2", "Tom");
      l.put("3", "Jimmy");
      l.put("4", "Morgan");
      l.put("5", "Tim");
      l.put("6", "Brad");
      System.out.println("LinkedHashMap elements...");
      Collection res = l.values();
      Iterator i = res.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

Output

LinkedHashMap elements...
Jack
Tom
Jimmy
Morgan
Tim
Brad
raja
Published on 30-Jan-2019 07:16:29
Advertisements