drop confusing first(cond) methods; introduce reduce(f); wrap iterator

This commit is contained in:
Gregory.Shrago
2018-05-22 03:04:54 +03:00
parent 3abc3318bf
commit 7923546ada
2 changed files with 18 additions and 22 deletions
@@ -377,9 +377,10 @@ public class TreeTraverserTest extends TestCase {
}
public void testJoin() {
assertNull(JBIterable.<String>of().join(", ").reduce((a, b) -> a + b));
assertEquals("", JBIterable.of().join(", ").reduce("", (a, b) -> a + b));
assertEquals("a", JBIterable.of("a").join(", ").reduce("", (a, b) -> a + b));
assertEquals("a, b, c", JBIterable.of("a", "b", "c").join(", ").reduce("", (a, b) -> a + b));
assertEquals("a", JBIterable.of("a").join(", ").reduce((a, b) -> a + b));
assertEquals("a, b, c", JBIterable.of("a", "b", "c").join(", ").reduce((a, b) -> a + b));
}
public void testSplits1() {
@@ -100,7 +100,7 @@ public abstract class JBIterable<E> implements Iterable<E> {
Multi(Iterable<? extends E> iterable) { super(iterable);}
public Iterator<E> iterator() {
return ((Iterable<E>)content).iterator();
return JBIterator.from(((Iterable<E>)content).iterator());
}
}
@@ -571,24 +571,6 @@ public abstract class JBIterable<E> implements Iterable<E> {
return iterator.hasNext() ? iterator.next() : null;
}
/**
* Returns the first element if it is an instance of the specified class, otherwise null.
*/
@Nullable
public final <T> T first(@NotNull Class<T> type) {
E first = first();
return first != null && type.isInstance(first) ? (T)first : null;
}
/**
* Returns the first element if it satisfies the condition, otherwise null.
*/
@Nullable
public final E first(@NotNull Condition<? super E> condition) {
E first = first();
return first != null && condition.value(first) ? first : null;
}
/**
* Returns the first element if it is the only one, otherwise null.
*/
@@ -639,7 +621,20 @@ public abstract class JBIterable<E> implements Iterable<E> {
}
/**
* Returns the index of the first matching element.
* Perform calculation over this iterable.
*/
public final E reduce(@NotNull PairFunction<E, ? super E, E> function) {
boolean first = true;
E cur = null;
for (E e : this) {
if (first) { cur = e; first = false; }
else cur = function.fun(cur, e);
}
return cur;
}
/**
* Returns the the first matching element.
*/
public final E find(@NotNull Condition<? super E> condition) {
return filter(condition).first();