1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor.core.algorithm;
18
19 import java.io.Serializable;
20
21 import org.apache.commons.functor.BinaryFunction;
22 import org.apache.commons.functor.UnaryPredicate;
23 import org.apache.commons.functor.UnaryProcedure;
24 import org.apache.commons.functor.generator.Generator;
25
26
27
28
29
30
31 public final class IndexOfInGenerator<T>
32 implements BinaryFunction<Generator<? extends T>, UnaryPredicate<? super T>, Number>, Serializable {
33
34
35
36 private static final long serialVersionUID = -11365986575536471L;
37 private static final IndexOfInGenerator<Object> INSTANCE = new IndexOfInGenerator<Object>();
38
39
40
41
42 private static class IndexProcedure<T> implements UnaryProcedure<T> {
43 private final Generator<? extends T> generator;
44 private final UnaryPredicate<? super T> pred;
45 private long index = -1L;
46 private long current = 0L;
47
48
49
50
51
52 IndexProcedure(Generator<? extends T> generator, UnaryPredicate<? super T> pred) {
53 this.generator = generator;
54 this.pred = pred;
55 }
56
57
58
59
60 public void run(T obj) {
61 if (index < 0 && pred.test(obj)) {
62 index = current;
63 generator.stop();
64 }
65 current++;
66 }
67 }
68
69
70
71
72
73
74 public Number evaluate(Generator<? extends T> left, UnaryPredicate<? super T> right) {
75 IndexProcedure<T> findProcedure = new IndexProcedure<T>(left, right);
76 left.run(findProcedure);
77 return findProcedure.index;
78 }
79
80
81
82
83 public boolean equals(Object obj) {
84 return obj == this || obj != null && obj.getClass().equals(getClass());
85 }
86
87
88
89
90 public int hashCode() {
91 return System.identityHashCode(INSTANCE);
92 }
93
94
95
96
97
98 public static IndexOfInGenerator<Object> instance() {
99 return INSTANCE;
100 }
101 }