Tuesday 9 May 2023

Get the enumeration from an Iterator in Java

Below snippet return an enumeration from the iterator in Java.

private static <T> Enumeration<T> enumeration(Iterator<T> iterator) {
	return new Enumeration<T>() {

		public boolean hasMoreElements() {
			return iterator.hasNext();
		}

		public T nextElement() {
			return iterator.next();
		}
	};
}

 

Find the below working application.


 

EnumerationFromIteratorDemo.java
package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;

public class EnumerationFromIteratorDemo {

	private static <T> Enumeration<T> enumeration(Iterator<T> iterator) {
		return new Enumeration<T>() {

			public boolean hasMoreElements() {
				return iterator.hasNext();
			}

			public T nextElement() {
				return iterator.next();
			}
		};
	}

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

		Enumeration<Integer> enumeration = enumeration(primesCollection.iterator());
		while (enumeration.hasMoreElements()) {
			System.out.println(enumeration.nextElement());
		}
	}

}

 

Output

2
3
5
7
11

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Join the collection elements by a separator using streams

Get the stream from an iterator in Java

Get the stream from Enumeration in Java

LinkedHashTable implementation in Java

Get the enumeration from a Collection

No comments:

Post a Comment