• Java Data Structures Tutorial

Java Data Structures - Loop through a Set



The Set interface inherits the Iterator interface therefore it provides the iterator() method. This method returns the iterator object of the current set.

The iterator object allows you can invoke two methods namely

  • hasNext() − This method verifies whether the current object contains more elements if so it returns true.

  • next() − This method returns the next element of the current object.

Using these two methods you can you can loop through a set in Java.

Example

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class LoopThroughSet {
   public static void main(String args[]) {      
      Set set = new HashSet();      
      set.add(100);
      set.add(501);
      set.add(302);
      set.add(420);
      System.out.println("Contents of the set are: ");
      Iterator iT = set.iterator();
      
      while( iT.hasNext()) {
         System.out.println(iT.next());     	  
      }   
   }
}

Output

Contents of the set are: 
100
420
501
302
Advertisements