Algorithm
-
Create a Set:
- Declare a Set variable of the desired type (e.g., HashSet, TreeSet) and instantiate it.
-
Add Elements to the Set:
- Use the
add
method to populate the Set with elements.
- Use the
-
Iterator Initialization:
- Obtain an iterator for the Set using the
iterator
method.
- Obtain an iterator for the Set using the
-
Iterate Over the Set:
- Use a loop (for, while, or enhanced for loop) to iterate through the Set.
- Check if there are more elements using the
hasNext
method of the iterator.
-
Retrieve Elements:
- Use the
next
method of the iterator to get the current element in the iteration.
- Use the
-
Process Each Element:
- Perform the desired operations or actions on each element during the iteration.
Code Examples
#1 Code Example- Iterate through Set using the forEach loop
Code -
Java Programming
import java.util.Set;
import java.util.HashSet;
class Main {
public static void main(String[] args) {
// Creating an set
Set < String> languages = new HashSet<>();
languages.add("Java");
languages.add("JavaScript");
languages.add("Python");
System.out.println("Set: " + languages);
// Using forEach loop
System.out.println("Iterating over Set using for-each loop:");
for(String language : languages) {
System.out.print(language);
System.out.print(", ");
}
}
}
Copy The Code &
Try With Live Editor
Output
Set: [Java, JavaScript, Python]`
Iterating over Set using for-each loop:
Java, JavaScript, Python,
Iterating over Set using for-each loop:
Java, JavaScript, Python,
#2 Code Example- Iterate through Set using iterator()
Code -
Java Programming
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
class Main {
public static void main(String[] args) {
// Creating an Set
Set < Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(3);
numbers.add(2);
System.out.println("Set: " + numbers);
// Creating an instance of Iterator
Iterator < Integer> iterate = numbers.iterator();
System.out.println("Iterating over Set:");
while(iterate.hasNext()) {
System.out.print(iterate.next() + ", ");
}
}
}
Copy The Code &
Try With Live Editor
Output
Set: [1, 2, 3]
Iterating over Set:
1, 2, 3,
Iterating over Set:
1, 2, 3,
#3 Code Example- Iterate through Set using forEach() method
Code -
Java Programming
import java.util.Set;
import java.util.HashSet;
class Main {
public static void main(String[] args) {
// create an Set
Set < Integer> numbers = new HashSet<>();
// add elements to the HashSet
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("Set: " + numbers);
// iterate each element of the set
System.out.print("Element of Set: ");
// access each element using forEach() method
// pass lambda expression to forEach()
numbers.forEach((e) -> {
System.out.print(e + " ");
});
}
}
Copy The Code &
Try With Live Editor
Output
Set: [1, 2, 3, 4]
Element of Set: 1 2 3 4
Element of Set: 1 2 3 4
Demonstration
Java Programing Example to Iterate over a Set-DevsEnv