How can I Convert an Iterator to Set in Java

How can I convert an Iterator into a Set in Java?

Suppose I have an iterator iter and a set set.

Iterator<T> iter;

1. Using for loops

Iterators provide a way to access the elements of an object sequentially without exposing its underlying representation.

Naturally, we can sequentially access each element and add it to a set.

Set<T> set = new HashSet<>();
while (iterator.hasNext()) {
  T obj = iterator.next();
  set.add(obj);
}

2. Using Guava

We can also use Guava’s Sets.newHashSet() to create a mutable set containing the elements that the iterator would access.

Set<T> set = Sets.newHashSet(iter);

3. Using Apache Commons Collections

If we have access to Apache Commons Collections, we can use IteratorUtils.toList() to convert the iterator to a list. Then, we can convert the list to a set.

Set<T> set = new HashSet<>(IteratorUtils.toList(iter));

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *