Saturday 12 November 2022

Convert an enumeration to Iterable in Java

Write a method that takes an enumeration as input and return an Iterable as output.

 

Signature

public static <T> Iterable<T> toIterable(final Enumeration<T> enumeration)

 

Find the below working application.

 


EnumerationToIterable.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class EnumerationToIterable {

	/**
	 * Convert an {@link Enumeration} to an {@link Iterable}
	 * 
	 * @param <T>
	 * @param enumeration
	 * @return empty list, if the enumeration is null, else return an iterable that
	 *         is used to traverse the elements of enumeraiton.
	 */

	public static <T> Iterable<T> toIterable(final Enumeration<T> enumeration) {
		if (enumeration == null) {
			return Collections.emptyList();
		}

		final Iterable<T> iterable = () -> new Iterator<T>() {
			@Override
			public boolean hasNext() {
				return enumeration.hasMoreElements();
			}

			@Override
			public T next() {
				return enumeration.nextElement();
			}
		};

		return iterable;
	}

	public static void main(String[] args) {
		final Vector<Integer> primesVector = new Vector<>();
		primesVector.addAll(Arrays.asList(2, 3, 5, 7, 11));

		final Enumeration<Integer> primesEnumeration = primesVector.elements();
		Iterable<Integer> iterable = toIterable(primesEnumeration);

		for (int i : iterable) {
			System.out.println(i);
		}
	}
}

 

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

Convert an iterator to set in Java

Convert an enumeration to set in Java

No comments:

Post a Comment