Iterate through elements of Java LinkedHashSet

Java 8Object Oriented ProgrammingProgramming

First, create a LinkedHashSet and add elements to it −

LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);
set.add(60);

Now, use the Iterator to iterate through the elements −

Iterator i = set.iterator();
   while (i.hasNext()) {
   System.out.println(i.next());
}

The following is an example to iterate through elements of LinkedHashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
      set.add(10);
      set.add(20);
      set.add(30);
      set.add(40);
      set.add(50);
      set.add(60);
      System.out.println("LinkedHashSet...");
      System.out.println(set);
      System.out.println("Iterating...");
      Iterator i = set.iterator();
      while (i.hasNext()){
         System.out.println(i.next());
      }
   }
}

Output

LinkedHashSet...
[10, 20, 30, 40, 50, 60]
Iterating...
10
20
30
40
50
60
raja
Published on 30-Jan-2019 10:54:47
Advertisements