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

ID : 10161

viewed : 31

Tags : javaloopssethashsetjava

Top 5 Answer for java - How to Iterate over a Set/HashSet without an Iterator?

vote vote

99

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); 
vote vote

90

There are at least six additional ways to iterate over a set. The following are known to me:

Method 1

// Obsolete Collection Enumeration e = new Vector(movies).elements(); while (e.hasMoreElements()) {   System.out.println(e.nextElement()); } 

Method 2

for (String movie : movies) {   System.out.println(movie); } 

Method 3

String[] movieArray = movies.toArray(new String[movies.size()]); for (int i = 0; i < movieArray.length; i++) {   System.out.println(movieArray[i]); } 

Method 4

// Supported in Java 8 and above movies.stream().forEach((movie) -> {   System.out.println(movie); }); 

Method 5

// Supported in Java 8 and above movies.stream().forEach(movie -> System.out.println(movie)); 

Method 6

// Supported in Java 8 and above movies.stream().forEach(System.out::println); 

This is the HashSet which I used for my examples:

Set<String> movies = new HashSet<>(); movies.add("Avatar"); movies.add("The Lord of the Rings"); movies.add("Titanic"); 
vote vote

74

Converting your set into an array may also help you for iterating over the elements:

Object[] array = set.toArray();  for(int i=0; i<array.length; i++)    Object o = array[i]; 
vote vote

62

To demonstrate, consider the following set, which holds different Person objects:

Set<Person> people = new HashSet<Person>(); people.add(new Person("Tharindu", 10)); people.add(new Person("Martin", 20)); people.add(new Person("Fowler", 30)); 

Person Model Class

public class Person {     private String name;     private int age;      public Person(String name, int age) {         this.name = name;         this.age = age;     }      //TODO - getters,setters ,overridden toString & compareTo methods  } 
  1. The for statement has a form designed for iteration through Collections and arrays .This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read.
for(Person p:people){   System.out.println(p.getName()); } 
  1. Java 8 - java.lang.Iterable.forEach(Consumer)
people.forEach(p -> System.out.println(p.getName())); 
default void forEach(Consumer<? super T> action)  Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:  The default implementation behaves as if:   for (T t : this)      action.accept(t);  Parameters: action - The action to be performed for each element  Throws: NullPointerException - if the specified action is null  Since: 1.8 
vote vote

57

You can use functional operation for a more neat code

Set<String> set = new HashSet<String>();  set.forEach((s) -> {      System.out.println(s); }); 

Top 3 video Explaining java - How to Iterate over a Set/HashSet without an Iterator?

Related QUESTION?