blob: 5871102f1fb2373b1b4832aed94a33fb4ecc3106 (
plain) (
blame)
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
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.result;
import java.util.*;
/**
* An iterator for the forest of hits in a result.
*
* @author havardpe
*/
public class DeepHitIterator implements Iterator<Hit> {
private final boolean ordered;
private List<Iterator<Hit>> stack;
private boolean canRemove = false;
private Iterator<Hit> it = null;
private Hit next = null;
/**
* Create a deep hit iterator based on the given hit iterator.
*
* @param it The hits iterator to traverse.
* @param ordered Whether or not the hits should be ordered.
*/
public DeepHitIterator(Iterator<Hit> it, boolean ordered) {
this.ordered = ordered;
this.it = it;
}
@Override
public boolean hasNext() {
canRemove = false;
return getNext();
}
@Override
public Hit next() throws NoSuchElementException {
if (next == null && !getNext()) {
throw new NoSuchElementException();
}
Hit ret = next;
next = null;
canRemove = true;
return ret;
}
@Override
public void remove() throws UnsupportedOperationException, IllegalStateException {
if (!canRemove) {
throw new IllegalStateException("Can not remove() an element after calling hasNext().");
}
it.remove();
}
private boolean getNext() {
if (next != null) {
return true;
}
if (stack == null) {
stack = new ArrayList<>();
}
while (true) {
if (it.hasNext()) {
Hit hit = it.next();
if (hit instanceof HitGroup) {
stack.add(it);
if (ordered) {
it = ((HitGroup)hit).iterator();
} else {
it = ((HitGroup)hit).unorderedIterator();
}
} else {
next = hit;
return true;
}
} else if (!stack.isEmpty()) {
it = stack.remove(stack.size()-1);
} else {
return false;
}
}
}
}
|