Iterator and loop HashSet in java

In this tutorial we will learn how to Iterator HashSet or loop Hashset in java.

In looping Hashset we use two ways.

1. Iterator,
2. for loop

See Example

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import port java.util.List;

public class Example1 {
 public static void main(String args[]) {
     // HashSet declaration
HashSet<String> hashset = getHashSet();
 
   }
  public static   HashSet<String> getHashSet(){
// Adding elements to the HashSet
HashSet<String> hashset  =  new HashSet<String>();
      hashset.add("Item4");
      hashset.add("Item2");
      hashset.add("Item6");
      hashset.add("Item1");
      hashset.add("Item3");
      hashset.add("Item5");
   
      // Creating an Array (convert hashset to Array
      System.out.println("--For Loop --");
      for(String str : hashset){
          System.out.println(str);
         }
      //Iterator HashSet
      System.out.println("Iterator hashset ");
      Iterator<String> it = hashset.iterator();
      while(it.hasNext()){
         System.out.println(it.next());
      }
      return hashset;
}
}

// result :

--For Loop --
Item1
Item2
Item5
Item6
Item3
Item4
Iterator hashset
Item1
Item2
Item5
Item6
Item3
Item4





EmoticonEmoticon