-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathArrayZipWithIndexExample.java
More file actions
executable file
·67 lines (53 loc) · 2.19 KB
/
ArrayZipWithIndexExample.java
File metadata and controls
executable file
·67 lines (53 loc) · 2.19 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
64
65
66
67
package spliterators.part2.example;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
public class ArrayZipWithIndexExample {
public static class IndexedArraySpliterator<T> extends Spliterators.AbstractSpliterator<IndexedPair<T>> {
private final T[] array;
private int startInclusive;
private final int endExclusive;
public IndexedArraySpliterator(T[] array) {
this(array, 0, array.length);
}
private IndexedArraySpliterator(T[] array, int startInclusive, int endExclusive) {
super(endExclusive - startInclusive,
Spliterator.IMMUTABLE | Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL);
this.array = array;
this.startInclusive = startInclusive;
this.endExclusive = endExclusive;
}
@Override
public boolean tryAdvance(Consumer<? super IndexedPair<T>> action) {
if (startInclusive < endExclusive) {
action.accept(new IndexedPair<>(startInclusive, array[startInclusive]));
startInclusive += 1;
return true;
} else {
return false;
}
}
@Override
public void forEachRemaining(Consumer<? super IndexedPair<T>> action) {
for (int i = startInclusive; i < endExclusive; i++) {
action.accept(new IndexedPair<>(i, array[i]));
}
startInclusive = endExclusive;
}
@Override
public long estimateSize() {
return endExclusive - startInclusive;
}
@Override
public IndexedArraySpliterator<T> trySplit() {
int length = endExclusive - startInclusive;
if (length <= 1) {
return null;
}
int middle = startInclusive + length/2;
final IndexedArraySpliterator<T> newSpliterator = new IndexedArraySpliterator<>(array, startInclusive, middle);
startInclusive = middle;
return newSpliterator;
}
}
}