Handle Enumeration <T> as Iterator <T>

I have a class that implements the Enumeration<T> interface, but the Java foreach loop requires an Iterator<T> interface. Is there an Enumeration to Iterator adapter in the standard Java library?

+13
java iterator foreach enumeration adapter
Feb 15 '11 at 17:24
source share
7 answers

You need the so-called β€œAdapter” to adapt Enumeration to an Iterator incompatible with other parameters. Apache collection collections have an EnumerationIterator . Using:

 Iterator iterator = new EnumerationIterator(enumeration); 
+9
Feb 15 '11 at 17:35
source share

If you just want something to be repeated in a for-each loop (so that Iterable and not only Iterator), always java.util.Collections.list(Enumeration<T> e) (without using any external libraries).

+27
Sep 26 '13 at 14:51
source share

a) I'm sure you mean Enumeration , not Enumerator
b) Guava provides the Helper method Iterators.forEnumeration(enumeration) which generates an iterator from Enumeration, but that will not help you either, since you need Iterable (the iterator provider), not Iterator
c) you can do this with this helper class:

 public class WrappingIterable<E> implements Iterable<E>{ private Iterator<E> iterator; public WrappingIterable(Iterator<E> iterator){ this.iterator = iterator; } @Override public Iterator<E> iterator(){ return iterator; } } 

And now your client code will look like this:

 for(String string : new WrappingIterable<String>( Iterators.forEnumeration(myEnumeration))){ // your code here } 

But is it worth the effort?

+7
Feb 15 '11 at 17:37
source share

No need to collapse by yourself. Check out the Google Guava library. Specifically

 Iterators.forEnumeration() 
+3
Feb 15 '11 at 17:38
source share

There is nothing that is part of the standard library. Unfortunately, you will have to flip your own adapter. There are examples of what others have done, for example:

IterableEnumerator

+2
Feb 15 '11 at 17:31
source share

or in collections of EnumerationUtils collections

import static org.apache.commons.collections.EnumerationUtils.toList

 toList(myEnumeration) 
+1
Feb 28 '13 at 12:46
source share

If you can change the class, you can simply implement Iterator<T> and add the remove method.

0
Feb 15 2018-11-15T00:
source share



All Articles