mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
add IterChain
This commit is contained in:
parent
f9b6110042
commit
691ccd0f3d
@ -10,6 +10,7 @@
|
||||
* 【all 】 JWT模块加入到all和bom包中(issue#1654@Github)
|
||||
* 【core 】 CollUtil删除所有Map相关操作
|
||||
* 【all 】 **重要!** 删除过期方法
|
||||
* 【core 】 增加IterChian类
|
||||
|
||||
### 🐞Bug修复
|
||||
|
||||
|
@ -0,0 +1,90 @@
|
||||
package cn.hutool.core.collection;
|
||||
|
||||
import cn.hutool.core.lang.Chain;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* 组合{@link Iterator},将多个{@link Iterator}组合在一起,便于集中遍历。<br>
|
||||
* 来自Jodd
|
||||
*
|
||||
* @param <T> 元素类型
|
||||
* @author looly, jodd
|
||||
*/
|
||||
public class IterChain<T> implements Iterator<T>, Chain<Iterator<T>, IterChain<T>> {
|
||||
|
||||
protected final List<Iterator<T>> allIterators = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 构造
|
||||
* 可以使用 {@link #addChain(Iterator)} 方法加入更多的集合。
|
||||
*/
|
||||
public IterChain() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new composite iterator with provided iterators.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public IterChain(Iterator<T>... iterators) {
|
||||
for (final Iterator<T> iterator : iterators) {
|
||||
addChain(iterator);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IterChain<T> addChain(Iterator<T> iterator) {
|
||||
if (allIterators.contains(iterator)) {
|
||||
throw new IllegalArgumentException("Duplicate iterator");
|
||||
}
|
||||
allIterators.add(iterator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- interface
|
||||
|
||||
protected int currentIter = -1;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
if (currentIter == -1) {
|
||||
currentIter = 0;
|
||||
}
|
||||
|
||||
final int size = allIterators.size();
|
||||
for (int i = currentIter; i < size; i++) {
|
||||
final Iterator<T> iterator = allIterators.get(i);
|
||||
if (iterator.hasNext()) {
|
||||
currentIter = i;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T next() {
|
||||
if (false == hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
return allIterators.get(currentIter).next();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
if (-1 == currentIter) {
|
||||
throw new IllegalStateException("next() has not yet been called");
|
||||
}
|
||||
|
||||
allIterators.get(currentIter).remove();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<Iterator<T>> iterator() {
|
||||
return this.allIterators.iterator();
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user