introduce: map, reduce, find, indexOf and flatMap

This commit is contained in:
Gregory.Shrago
2016-07-30 01:27:38 +03:00
parent 5e01863b26
commit 216b92b438
2 changed files with 62 additions and 0 deletions
@@ -289,6 +289,16 @@ public class TreeTraverserTest extends TestCase {
assertEquals(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21), it.toList());
}
public void testFindIndexReduceMap() {
JBIterable<Integer> it = JBIterable.of(1, 2, 3, 4, 5);
assertEquals(15, (int)it.reduce(0, (Integer v, Integer o) -> v + o));
assertEquals(3, (int)it.find((o)-> o.intValue() == 3));
assertEquals(2, it.indexOf((o)-> o.intValue() == 3));
assertEquals(-1, it.indexOf((o)-> o.intValue() == 33));
assertEquals(Arrays.asList(1, 4, 9, 16, 25), it.map(o -> o * o).toList());
assertEquals(Arrays.asList(0, 1, 0, 2, 0, 3, 0, 4, 0, 5), it.flatMap(o -> ContainerUtil.list(0, o)).toList());
}
// TreeTraversal ----------------------------------------------
@NotNull
@@ -430,6 +430,58 @@ public abstract class JBIterable<E> implements Iterable<E> {
return cur;
}
/**
* Perform calculation over this iterable.
*/
public final <T> T reduce(@Nullable T first, @NotNull PairFunction<T, E, T> function) {
T cur = first;
for (E e : this) {
cur = function.fun(cur, e);
}
return cur;
}
/**
* Returns the index of the first matching element.
*/
public final E find(@NotNull Condition<E> condition) {
return filter(condition).first();
}
/**
* Returns the index of the matching element.
*/
public final int indexOf(@NotNull Condition<E> condition) {
int index = 0;
for (E e : this) {
if (condition.value(e)) {
return index;
}
index ++;
}
return -1;
}
/**
* Synonym for transform()
*
* @see JBIterable#transform(Function)
*/
@NotNull
public final <T> JBIterable<T> map(@NotNull Function<? super E, T> function) {
return transform(function);
}
/**
* "Maps" and "flattens" this iterable.
*
* @see JBIterable#transform(Function)
*/
@NotNull
public final <T> JBIterable<T> flatMap(Function<? super E, ? extends Iterable<? extends T>> function) {
return map(function).flatten(Function.ID);
}
/**
* Determines whether this iterable is empty.
*/