Saturday 12 November 2022

Convert an iterator to set in Java

Write a function toSet, that takes an iterator as an argument and return the set as output.

 

Signature

public static <T> Set<T> toSet(Iterator<T> iterator)

 

Find the below working application.


 

IteratorToSet.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class IteratorToSet {

	/**
	 * Convert an {@link Iterator} to the {@link Set}
	 * 
	 * @param <T>
	 * @param iterator
	 * 
	 * @return empty set, if the iterator is null, else return a set that contain
	 *         the elements from iterator
	 */
	public static <T> Set<T> toSet(Iterator<T> iterator) {

		if (iterator == null) {
			return Collections.emptySet();
		}

		final Set<T> set = new HashSet<>();

		while (iterator.hasNext()) {
			set.add(iterator.next());
		}

		return set;
	}

	public static void main(String[] args) {
		Iterator<Integer> primesIter = Arrays.asList(2, 3, 5, 7, 11).iterator();

		Set<Integer> primesSet = toSet(primesIter);
		System.out.println(primesSet);
	}

}

 

Output

[2, 3, 5, 7, 11]

 

 

  

You may like

Interview Questions

Collection programs in Java

Array programs in Java

How to check the object is an iterable or not?

How to check the type or object is a map or not?

Get a map from array in Java

Get reverse iterator for the given array in Java

Convert primitive array to wrapper array in Java

No comments:

Post a Comment