In this post, we 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:
Java
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 SetUtil { // Iterate over 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 set is modified after the iterator is created except through the iterator’s own remove method.
2. Using enhanced for loop:
As Set
implements Iterable
Interface, we can use enhanced for loop to loop through set as shown below:
Java
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 SetUtil { // Iterate over 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 Streams
In Java 8 and above, we can loop over a set with the help of streams, lambdas and forEach as shown below –
Java
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 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; class SetUtil { // Iterate over 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()
function and then print it using Arrays.toString()
function. There are many implementations of toArray()
method as shown below:
Java
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 SetUtil { // Iterate over Set in Java public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays.asList("C++", "Java", "Go")); // Convert list to 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
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.
Java
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 |
import java.util.*; class SetUtil { // Iterate over 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 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 contents of the set, we can simply print the string representation of set using toString()
function as shown below:
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; class SetUtil { // Iterate over 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); } } |
Related Posts:
5 ways to Iterate Map using keySet() in Java
5 ways to Iterate Map in Java using entrySet()
Thanks for reading.
Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
Leave a Reply