Set (HashSet) Iterator Example

In this example, we will write a Java code to iterate over a HashSet using the Iterator interface.

Set (HashSet) Iterator Example

Here is the example to iterate over a HashSet using Iterator interface:
package com.java.tutorials.collections;

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

/**
 * Iterator Examples
 * @author Ramesh Fadatare
 *
 */
public class IteratorExample {
 public static void main(String[] args) {
  
  Set<String> fruits = new HashSet<String>();
  fruits.add("Banana");
  fruits.add("Apple");
  fruits.add("Mango");
  fruits.add("Orange");
  
  Iterator<String> iterator = fruits.iterator();
  while (iterator.hasNext()) {
   String fruit = (String) iterator.next();
   
   if("Apple".equals(fruit)) {
    iterator.remove();
   }
  }
  System.out.println(fruits);
  
 }
}
Output:
[Mango, Orange, Banana]

References

Comments