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
// CherryChallenge
EasyCreate 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap5HashSet Part 2
Math - Union of HashSetsMath - Intersection of HashSetMath - Set DifferenceMath - Symmetric DifferenceSubsets and SupersetsIterating Over Sets