Skip to content

Instantly share code, notes, and snippets.

@adjam
Created September 8, 2016 19:34
Show Gist options
  • Save adjam/25f615af87ea6e5bfdbcead32c7e313d to your computer and use it in GitHub Desktop.
Save adjam/25f615af87ea6e5bfdbcead32c7e313d to your computer and use it in GitHub Desktop.
Java decorator for marc4j MarcReader class to allow it to be using as an Iterator or a Java 8 Stream
package edu.example.lib.marc;
import org.marc4j.MarcReader;
import org.marc4j.marc.Record;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Wrapper for marc4j <code>MarcReader</code> that acts as an iterator and provides Java 8 Stream functionality.
*/
public class RecordIterator implements Iterator<Record> {
private final MarcReader wrappedReader;
public RecordIterator(MarcReader wrappedReader) {
this.wrappedReader = wrappedReader;
}
@Override
public boolean hasNext() {
return wrappedReader.hasNext();
}
@Override
public Record next() {
return wrappedReader.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove() not supported on this class");
}
@Override
public void forEachRemaining(Consumer<? super Record> action) {
while( wrappedReader.hasNext() ) {
action.accept(wrappedReader.next());
}
}
public Stream<Record> asStream() {
Spliterator<Record> spliterator = Spliterators.spliteratorUnknownSize(this, Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.IMMUTABLE);
return StreamSupport.stream( spliterator, false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment