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
Join the collection elements by a separator using streams
Get the stream from an iterator in Java
Get the stream from Enumeration in Java
No comments:
Post a Comment