我有一个大小为100的字符串迭代器。我想每次得到10个元素并把它们传递给另一个函数。除了在循环中创建条件来计数10个元素之外,还有其他方法/方法吗?
这取决于你需要如何处理它们,但从你写问题的方式来看,你似乎想一次处理10个项目。
Iterator<String> it = ... ;
List<String> nextBatch = nextBatchOf(it, 10);
// do something with nextBatch
和获取下一批元素
的方法List<String> nextBatchOf(Iterator<String> it, int size) {
List<String> batch = new ArrayList<>();
for (int i = 0; i < size && it.hasNext(); i++) {
batch.add(it.next());
}
return batch;
}
您可以使用标准数组API:
int step = 10;
for (int i = 0; i < 10; i ++){
anotherFunction(Arrays.copyOfRange(source, i * step, (i + 1) * step));
}