To iterate through the elements of a HashSet
object in Java 8, you can use the forEach
method of the Set
interface, which is implemented by the HashSet
class.
Here is an example of how you can use the forEach
method to print the elements of a HashSet
:
HashSet<String> set = new HashSet<>(); set.add("element1"); set.add("element2"); set.add("element3"); set.forEach(System.out::println);
This will print the elements of the HashSet
in the order they were added.
Keep in mind that the HashSet
class does not maintain the order in which the elements were added, so the order in which the elements are printed may not be the same as the order in which they were added. If you need to maintain the insertion order, you can use a LinkedHashSet
instead of a HashSet
.
You can also use the for-each
loop or the Iterator
class to iterate through the elements of a HashSet
. Here is an example using the for-each
loop:
HashSet<String> set = new HashSet<>(); set.add("element1"); set.add("element2"); set.add("element3"); for (String element : set) { System.out.println(element); }
And here is an example using the Iterator
class:
HashSet<String> set = new HashSet<>(); set.add("element1"); set.add("element2"); set.add("element3"); Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { String element = iterator.next(); System.out.println(element); }