Iterate over a Set in Java
This post will discuss various methods to iterate over set in Java.
1. Using Iterator
We can use iterator() that returns an iterator to iterate over a set, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; class Main { // Iterate over a set in Java public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays.asList("C++", "Java", "Go")); // 1. Returns an iterator over the elements in this set Iterator<String> it = set.iterator(); while (it.hasNext()) { System.out.println(it.next()); } // 2. Use `forEachRemaining()` provided by `java.util.Iterator` interface set.iterator().forEachRemaining(System.out::println); } } |
Please note that the iterator will throw a ConcurrentModificationException if the set is modified after it is created except through the iterator’s own remove method.
2. Using enhanced for-loop
As Set implements the Iterable interface, we can use enhanced for-loop to loop through the set, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; class Main { // Iterate over a set in Java public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays.asList("C++", "Java", "Go")); // enhanced for-loop also uses an iterator behind the scenes for (String item: set) { System.out.println(item); } } } |
3. Java 8 – Converting set to stream
In Java 8 and above, we can loop over a set with the help of streams, lambdas, and forEach, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; class Main { // Iterate over a set in Java public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays.asList("C++", "Java", "Go")); // 1. Get stream and use lambda expression set.stream().forEach(S -> System.out.println(S)); // 2. Or by providing method reference set.stream().forEach(System.out::println); // 3. Set inherit `forEach()` from `java.lang.Iterable` interface set.forEach(System.out::println); // 4. Stream.of() + toArray() Stream.of(set.toArray()).forEach(System.out::println); } } |
4. Converting set to array
We can first convert the set into an array using toArray() method and then print it using Arrays.toString() method. There are many implementations of toArray() method, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import java.util.Arrays; import java.util.HashSet; import java.util.Set; class Main { // Iterate over a set in Java public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays.asList("C++", "Java", "Go")); // Convert a list to an array String[] array = null; // 1. Using `Set.toArray(T[])` method array = set.toArray(new String[set.size()]); System.out.println(Arrays.toString(array)); // 2. `Set.toArray(T[])` – without allocating any memory array = set.toArray(new String[0]); System.out.println(Arrays.toString(array)); // 3. Using `Set.toArray()` method System.out.println(Arrays.toString(set.toArray())); // 4. Java 8 – Streams + method references array = set.stream().toArray(String[]::new); System.out.println(Arrays.toString(array)); // 5. Java 8 – Streams + lambda expressions array = set.stream().toArray(n -> new String[n]); System.out.println(Arrays.toString(array)); // 6. Using `FluentIterable` class from Guava library array = FluentIterable.from(set).toArray(String.class); System.out.println(Arrays.toString(array)); // 7. Using `Iterables` class from Guava library array = Iterables.toArray(set, String.class); System.out.println(Arrays.toString(array)); } } |
5. Converting set to vector
The Enumeration interface provides methods to enumerate through the elements of a Vector. So, we can convert the set into a vector and finally print all elements of that vector.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.*; class Main { // Iterate over a set in Java public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays.asList("C++", "Java", "Go")); // 1. Convert the set into a vector @Deprecated Enumeration<String> enumeration = new Vector(set).elements(); // if enumeration contains more elements while (enumeration.hasMoreElements()) { // print the next element of the enumeration System.out.println(enumeration.nextElement()); } // 2. Collections.enumeration() returns an enumeration over the // specified collection enumeration = Collections.enumeration(set); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } } } |
6. Converting set to string
If we’re only required to display the contents of the set, we can simply print the string representation of the set using the toString() method, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; class Main { // Iterate over a set in Java public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays.asList("C++", "Java", "Go")); // 1. Print string representation of the set using `toString()` System.out.println(set.toString()); // 2. Java 8 way! Stream.of(set.toString()).forEach(System.out::println); } } |
That’s all about iterating over a Set in Java.
Related Posts:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)