Skip to content

Commit

Permalink
Resolve #22. More general reduce interface
Browse files Browse the repository at this point in the history
  • Loading branch information
aNNiMON committed Jan 22, 2016
1 parent 48bdf90 commit 820ef8b
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/main/java/com/annimon/stream/Stream.java
Original file line number Diff line number Diff line change
Expand Up @@ -641,13 +641,31 @@ public void forEach(final Consumer<? super T> action) {
* @param accumulator the accumulation function
* @return the result of the reduction
*/
public T reduce(final T identity, BiFunction<T, T, T> accumulator) {
/*public T reduce(final T identity, BiFunction<T, T, T> accumulator) {
T result = identity;
while (iterator.hasNext()) {
final T value = iterator.next();
result = accumulator.apply(result, value);
}
return result;
}*/

/**
* Reduces the elements using provided identity value and the associative accumulation function.
*
* <p>This is a terminal operation.
*
* @param identity the initial value
* @param accumulator the accumulation function
* @return the result of the reduction
*/
public <R> R reduce(R identity, BiFunction<? super R, ? super T, ? extends R> accumulator) {
R result = identity;
while (iterator.hasNext()) {
final T value = iterator.next();
result = accumulator.apply(result, value);
}
return result;
}

/**
Expand Down
31 changes: 31 additions & 0 deletions src/test/java/com/annimon/stream/StreamTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,18 @@ public void testReduceSumFromMinus45() {
assertEquals(0, result);
}

@Test
public void testReduceWithAnotherType() {
int result = Stream.of("a", "bb", "ccc", "dddd")
.reduce(0, new BiFunction<Integer, String, Integer>() {
@Override
public Integer apply(Integer length, String s) {
return length + s.length();
}
});
assertEquals(10, result);
}

@Test
public void testReduceOptional() {
Optional<Integer> result = Stream.ofRange(0, 10)
Expand Down Expand Up @@ -538,6 +550,25 @@ public void testCollectWithSupplierAndAccumulator() {
assertEquals("abcdefg", text);
}

@Test
public void testCollect123() {
String string123 = Stream.of("1", "2", "3")
.collect(new Supplier<StringBuilder>() {
@Override
public StringBuilder get() {
return new StringBuilder();
}
}, new BiConsumer<StringBuilder, String>() {

@Override
public void accept(StringBuilder value1, String value2) {
value1.append(value2);
}
})
.toString();
assertEquals("123", string123);
}

@Test
public void testMin() {
Optional<Integer> min = Stream.of(6, 3, 9, 0, -7, 19)
Expand Down

0 comments on commit 820ef8b

Please sign in to comment.