-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathZipWithIndexDoubleSpliterator.java
More file actions
executable file
·70 lines (59 loc) · 2.2 KB
/
ZipWithIndexDoubleSpliterator.java
File metadata and controls
executable file
·70 lines (59 loc) · 2.2 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
package spliterators.part2.exercise;
import java.util.Comparator;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
public class ZipWithIndexDoubleSpliterator extends Spliterators.AbstractSpliterator<IndexedDoublePair> {
private final OfDouble inner;
private int currentIndex;
public ZipWithIndexDoubleSpliterator(OfDouble inner) {
this(0, inner);
}
private ZipWithIndexDoubleSpliterator(int firstIndex, OfDouble inner) {
super(inner.estimateSize(), IMMUTABLE | ORDERED | SORTED | SIZED | SUBSIZED | NONNULL);
currentIndex = firstIndex;
this.inner = inner;
}
@Override
public int characteristics() {
return IMMUTABLE | ORDERED | SORTED | SIZED | SUBSIZED | NONNULL;
}
@Override
public boolean tryAdvance(Consumer<? super IndexedDoublePair> action) {
if (inner.tryAdvance((double d) ->
action.accept(new IndexedDoublePair(currentIndex, d)))) {
currentIndex++;
return true;
}
return false;
}
@Override
public Comparator<? super IndexedDoublePair> getComparator() {
return (i1, i2) -> inner.getComparator().compare(i1.getValue(), i2.getValue());
}
@Override
public void forEachRemaining(Consumer<? super IndexedDoublePair> action) {
while (inner.tryAdvance((double d) ->
action.accept(new IndexedDoublePair(currentIndex, d)))) {
currentIndex++;
}
}
@Override
public Spliterator<IndexedDoublePair> trySplit() {
if (inner.hasCharacteristics(SUBSIZED)) {
return Optional.ofNullable(inner.trySplit())
.map(ofD -> {
int newCurrentIndex = currentIndex;
currentIndex += (int) ofD.estimateSize();
return new ZipWithIndexDoubleSpliterator(newCurrentIndex, ofD);})
.orElse(null);
} else {
return null;
}
}
@Override
public long estimateSize() {
return currentIndex + inner.estimateSize();
}
}