Last active
February 16, 2023 07:50
-
-
Save DaHoC/40d4e9006d6f86bfbd5fcb37cf64af93 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kaput.littlehelper; | |
import java.util.Enumeration; | |
import java.util.Iterator; | |
import java.util.NoSuchElementException; | |
import java.util.Objects; | |
/** | |
* Helper class to be able to use a{@link Iterator} (i.e. {@link java.util.stream.Stream}) with {@link Enumeration}. | |
* This can be useful, i.e.: | |
* <pre><code> | |
* Stream<InputStream> inputStreams = Streams.of(...); | |
* Enumeration<InputStream> inputStreamsEnumeration = new IteratorToEnumeration<>(inputStreams.iterator()); | |
* try (final SequenceInputStream sequenceInputStream = new SequenceInputStream(inputStreamsEnumeration)) {...} | |
* </code></pre> | |
* | |
* @param <T> type of elements to iterate/enumerate over | |
*/ | |
public class IteratorToEnumeration<T> implements Enumeration<T> { | |
private final Iterator<T> iterator; | |
/** | |
* Constructor to pass the {@link Iterator} and yield an {@link Enumeration}. | |
* | |
* @param iterator iterator must not be null | |
*/ | |
public IteratorToEnumeration(final Iterator<T> iterator) { | |
Objects.requireNonNull(iterator, "Iterator must not be null!"); | |
this.iterator = iterator; | |
} | |
@Override | |
public boolean hasMoreElements() { | |
return this.iterator.hasNext(); | |
} | |
@Override | |
public T nextElement() { | |
if (!this.iterator.hasNext()) { | |
throw new NoSuchElementException(); | |
} | |
return this.iterator.next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment