Saturday, 12 November 2022

Convert an Iterable to a Set in Java

Write a method, that takes an Iterable as input and return the set as output. Make sure that the order of elements is maintained.

 

Signature

public static <T> List<T> toSet(final Iterable<T> iterable, final boolean skipNull)

 

Find the below working application.

 


IterableToSet.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class IterableToSet {
	/**
	 * Converts an {@link Iterable} to a {@link Set}. If skipNull is set to true,
	 * then it skip the null values while constructing the {@link Set}
	 * 
	 * @param <T>
	 * @param iterable
	 * @param skipNull
	 * 
	 * @return empty list, if the {@link Iterable} is null or empty. else return a
	 *         {@link Set} that contain the elements of {@link Iterable}.
	 */
	public static <T> Set<T> toSet(final Iterable<T> iterable, final boolean skipNull) {

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

		if (iterable instanceof Set) {
			return (Set<T>) iterable;
		}

		// Return empty list, if the iterator has no elements
		if (!iterable.iterator().hasNext()) {
			return Collections.emptySet();
		}

		// Use LinkedHashSet to maintain the order
		final Set<T> set = new LinkedHashSet<>();
		for (T ele : iterable) {
			if (skipNull == true && ele == null) {
				continue;
			}
			set.add(ele);
		}

		return set;
	}

	public static void main(String[] args) {
		final List<Integer> primesList = Arrays.asList(2, 3, 5, 7, null, 11, 13);

		Set<Integer> set1 = toSet(primesList, true);
		Set<Integer> set2 = toSet(primesList, false);

		System.out.println(set1);
		System.out.println(set2);

	}

}

 

Output

[2, 3, 5, 7, 11, 13]
[2, 3, 5, 7, null, 11, 13]

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an enumeration to set in Java

Convert an enumeration to Iterable in Java

Convert an array to set in Java

Get the string representation of an Iterable

Convert an Iterable to List in Java

No comments:

Post a Comment