-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathZipWithArraySpliterator.java
More file actions
executable file
·86 lines (69 loc) · 3.02 KB
/
ZipWithArraySpliterator.java
File metadata and controls
executable file
·86 lines (69 loc) · 3.02 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package spliterators.part3.exercise;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
public class ZipWithArraySpliterator<A, B> extends Spliterators.AbstractSpliterator<Pair<A, B>> {
private final Spliterator<A> inner;
private int currentIndex;
private final B[] array;
private int arrayStartIndex;
private int arrayEndIndex;
public ZipWithArraySpliterator(Spliterator<A> inner, B[] array) {
this(0, inner, 0, 0, array);
}
private ZipWithArraySpliterator(int currentIndex, Spliterator<A> inner,
int arrayStartIndex, int arrayEndIndex, B[] array) {
super(inner.estimateSize(), ORDERED | SIZED | SUBSIZED | NONNULL | CONCURRENT);
this.inner = inner;
this.array = array;
this.currentIndex = currentIndex;
this.arrayStartIndex = arrayStartIndex;
this.arrayEndIndex = arrayEndIndex;
}
@Override
public int characteristics() {
return ORDERED | SIZED | SUBSIZED | NONNULL | CONCURRENT;
}
@Override
public boolean tryAdvance(Consumer<? super Pair<A, B>> action) {
if (currentIndex < array.length &&
inner.tryAdvance((a) -> action.accept(new Pair<>(a, array[currentIndex])))) {
currentIndex++;
return true;
}
return false;
}
@Override
public void forEachRemaining(Consumer<? super Pair<A, B>> action) {
while (currentIndex < array.length &&
inner.tryAdvance(a -> action.accept(new Pair<>(a, array[currentIndex])))) {
currentIndex++;
}
}
@Override
public Spliterator<Pair<A, B>> trySplit() {
if (inner.hasCharacteristics(SUBSIZED)) {
return Optional.ofNullable(inner.trySplit())
.map(newInner -> {
int newCurrentIndex = currentIndex;
currentIndex += (int) newInner.estimateSize();
arrayStartIndex = newCurrentIndex < array.length ? newCurrentIndex : array.length - 1;
arrayEndIndex = currentIndex < array.length ? currentIndex : array.length - 1;
Spliterator<Pair<A, B>> spliterator = new ZipWithArraySpliterator(newCurrentIndex, newInner,
arrayStartIndex, arrayEndIndex, array);
arrayStartIndex = currentIndex < array.length ? currentIndex : array.length - 1;
long newSizeOfSpltr = spliterator.estimateSize();
arrayEndIndex = newSizeOfSpltr < array.length ? (int) newSizeOfSpltr : array.length - 1;
return spliterator;
})
.orElse(null);
} else {
return null;
}
}
@Override
public long estimateSize() {
return currentIndex + inner.estimateSize();
}
}