Java Program to Iterate over a Set


In this article, we will understand how to iterate over a set. A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Below is a demonstration of the same −

Suppose our input is

Input set: [Java, Scala, Mysql, Python]

The desired output would be

Iterating over Set using for-each loop:
Java, Scala, Mysql, Python

Algorithm

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Create a hashset of values and initialize elements in it using the ‘add’ method.
Step 5 - Display the hashset on the console.
Step 6 - Iterate over the elements of the hashset, and fetch each value.
Step 7 - Display this on the console.
Step 8 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function. For-each

import java.util.Set;
import java.util.HashSet;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      Set<String> input_set = new HashSet<>();
      input_set.add("Java");
      input_set.add("Scala");
      input_set.add("Python");
      input_set.add("Mysql");
      System.out.println("The set is defined as: " + input_set);
      System.out.println("\nIterating over Set using for-each loop:");
      for(String elements : input_set) {
         System.out.print(elements);
         System.out.print(", ");
      }
   }
}

Output

The required packages have been imported
The set is defined as: [Java, Scala, Mysql, Python]

Iterating over Set using for-each loop:
Java, Scala, Mysql, Python,

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming. Iterator

import java.util.Set;
import java.util.HashSet;
public class Demo {
   static void print_set(Set<String> input_set){
      System.out.println("\nIterating over Set using for-each loop:");
      for(String elements : input_set) {
         System.out.print(elements);
         System.out.print(", ");
      }
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      Set<String> input_set = new HashSet<>();
      input_set.add("Java");
      input_set.add("Scala");
      input_set.add("Python");
      input_set.add("Mysql");
      System.out.println("The set is defined as: " + input_set);
      print_set(input_set);
   }
}

Output

The required packages have been imported
The set is defined as: [Java, Scala, Mysql, Python]

Iterating over Set using for-each loop:
Java, Scala, Mysql, Python,

Updated on: 30-Mar-2022

921 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements