Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Iterate over a Set/HashSet without an Iterator?

How can I iterate over a Set/HashSet without the following?

Iterator iter = set.iterator(); while (iter.hasNext()) {     System.out.println(iter.next()); } 
like image 262
user1621988 Avatar asked Sep 17 '12 08:09

user1621988


People also ask

Does Set have an iterator?

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.

How do you traverse a 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.


1 Answers

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); 
like image 132
assylias Avatar answered Oct 14 '22 01:10

assylias