Menu
Coddy logo textTech

Iterating Over Sets

Part of the Logic & Flow section of Coddy's Java journey — lesson 34 of 59.

Iterating over a set means going through each element one by one. Since a HashSet does not maintain a specific order, the order in which the elements are processed may differ from the order in which they were added.

First, create HashSet:

HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

Iterate over the set using a for‑each loop:

for (String fruit : fruits) {
   System.out.println(fruit);
}
// Apple
// Banana
// Cherry
challenge icon

Challenge

Easy

Create a method named <strong>printSet</strong> that takes a HashSet of strings as input and prints each element on a separate line.

Details:

  • The method should use a simple for‑each loop to iterate over the set.
  • Each element must be printed on its own line.

Cheat sheet

To iterate over a HashSet, use a for-each loop. Note that HashSet does not maintain insertion order:

HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

for (String fruit : fruits) {
   System.out.println(fruit);
}

Try it yourself

import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void printSet(HashSet<String> set) {
        // Write your code here using a for-each loop
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read a JSON string representing a HashSet of strings, e.g., ["Apple","Banana","Cherry"]
        String setString = scanner.nextLine();

        Type setType = new TypeToken<HashSet<String>>(){}.getType();
        HashSet<String> mySet = new Gson().fromJson(setString, setType);

        printSet(mySet);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow