Saturday, 12 November 2022

Convert an Iterable to List in Java

Write a method, that takes an Iterable as input and return the List as output.

 

Signature

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

 

Find the below working application.


IterableToList.java

package com.sample.app.collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class IterableToList {

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

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

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

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

		final List<T> list = new ArrayList<>();
		for (T ele : iterable) {
			if (skipNull == true && ele == null) {
				continue;
			}
			list.add(ele);
		}

		return list;
	}

	public static void main(String[] args) {
		Set<Integer> primesSet1 = new HashSet<>(Arrays.asList(2, 3, 5, 7, null, 11, 13));

		List<Integer> list1 = toList(primesSet1, true);
		List<Integer> list2 = toList(primesSet1, false);

		System.out.println(list1);
		System.out.println(list2);

	}

}

 

Output

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

 

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an iterator to set 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

No comments:

Post a Comment