com.github.azbh111.utils.java.iterable.model.MergedLazyIterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils-java Show documentation
Show all versions of utils-java Show documentation
com.github.azbh111:utils-java
The newest version!
package com.github.azbh111.utils.java.iterable.model;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @author: zyp
* @since: 2021/7/27 17:49
*/
public class MergedLazyIterator implements Iterator {
private final Iterator> sources;
private Iterator curSource;
/**
* 设置这个值, 指定最多迭代多少条数据
*
* @author zhengyongpan
* @since 2021/6/25 10:40
*/
private long limit = Long.MAX_VALUE;
private long count = 0;
public MergedLazyIterator(Iterator... sources) {
if (sources == null || sources.length == 0) {
this.sources = new EmptyIterator();
} else {
this.sources = (Iterator>) Arrays.asList(sources).iterator();
}
}
public MergedLazyIterator(Iterator> sources) {
if (sources == null) {
this.sources = new EmptyIterator();
} else {
this.sources = sources;
}
}
private void prepareNext() {
while (curSource == null || !curSource.hasNext()) {
closeCurrentSource();
if (sources.hasNext()) {
curSource = sources.next();
} else {
curSource = null;
break;
}
}
}
@Override
public boolean hasNext() {
if (count >= limit) {
closeCurrentSource();
return false;
}
if (curSource != null) {
if (curSource.hasNext()) {
return true;
}
closeCurrentSource();
}
prepareNext();
return curSource != null && curSource.hasNext();
}
private void closeCurrentSource() {
if (curSource != null && curSource instanceof Closeable) {
try {
((Closeable) curSource).close();
curSource = null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public T next() {
if (curSource == null) {
throw new NoSuchElementException();
}
T t = curSource.next();
count++;
return t;
}
public void setLimit(long limit) {
this.limit = limit;
}
}