-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChunkIterator.java
More file actions
63 lines (57 loc) · 1.26 KB
/
ChunkIterator.java
File metadata and controls
63 lines (57 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.*;
/**
Takes an iterator, loads n elements and returns them in bulk.
*/
class ChunkIterator<E> {
final int chunkSize;
final Iterator<E> it;
final boolean strict; // return last partial chunk or not
int chunkCnt = 1;
List<E> chunk;
public ChunkIterator(int size, Iterator<E> it, boolean strict) {
this.it = it;
this.chunkSize = size;
this.strict = strict;
}
public ChunkIterator(int size, Iterator<E> it) {
this(size, it, true);
}
public boolean hasNext() {
if (chunk != null) {
return true;
} else {
chunk = new ArrayList<E>();
int lineCnt = 0;
E line;
while (it.hasNext()){
line = it.next();
lineCnt += 1;
chunk.add(line);
// Util.log(line.substring(0,20));
if (lineCnt == chunkSize){ // chunk ready
Util.log("Create: "+chunkCnt+" with lines "+lineCnt);
chunkCnt += 1;
return true;
}
}
if (!strict && (lineCnt > 0)) {
List<E> partial = chunk.subList(0,lineCnt);
chunk = partial;
Util.log("Create: "+chunkCnt+" with lines "+lineCnt);
return true;
} else {
chunk = null;
return false;
}
}
}
public List<E> next() {
if(hasNext()){
List<E> res = chunk;
chunk = null;
return res;
} else {
throw new NoSuchElementException();
}
}
}