Java HashSet iterator() Method
Example
Use an iterator to loop through a set:
import java.util.HashSet;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Iterator<String> it = cars.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Definition and Usage
The iterator() method returns an Iterator object, which can be used to loop through the set.
A HashSet has no order, so the iterator does not return the items in the order they were added.
Tip: You can also remove items from the set while you loop, with the iterator's remove() method.
Syntax
public Iterator<T> iterator()
T refers to the data type of items in the set.
Parameter Values
None.
Technical Details
| Returns: | An Iterator object for the set. |
|---|