How can I iterate over a Set
/HashSet
without the following?
Iterator iter = set.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); }
Set iterator() method in Java with ExamplesSet. iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set.
Approach: To traverse a Set in reverse order, a reverse_iterator can be declared on it and it can be used to traverse the set from the last element to the first element with the help of rbegin() and rend() functions. Get the set. Declare the reverse iterator on this set.
You can use an enhanced for loop:
Set<String> set = new HashSet<String>(); //populate set for (String s : set) { System.out.println(s); }
Or with Java 8:
set.forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With