From 820ef8b4971b4dbbf1a3f637f930670ea2c02946 Mon Sep 17 00:00:00 2001 From: Victor Date: Fri, 22 Jan 2016 13:35:10 +0200 Subject: [PATCH] Resolve #22. More general reduce interface --- src/main/java/com/annimon/stream/Stream.java | 20 +++++++++++- .../java/com/annimon/stream/StreamTest.java | 31 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/annimon/stream/Stream.java b/src/main/java/com/annimon/stream/Stream.java index 5d4d6cc9..192a18ca 100644 --- a/src/main/java/com/annimon/stream/Stream.java +++ b/src/main/java/com/annimon/stream/Stream.java @@ -641,13 +641,31 @@ public void forEach(final Consumer action) { * @param accumulator the accumulation function * @return the result of the reduction */ - public T reduce(final T identity, BiFunction accumulator) { + /*public T reduce(final T identity, BiFunction 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. + * + *

This is a terminal operation. + * + * @param identity the initial value + * @param accumulator the accumulation function + * @return the result of the reduction + */ + public R reduce(R identity, BiFunction accumulator) { + R result = identity; + while (iterator.hasNext()) { + final T value = iterator.next(); + result = accumulator.apply(result, value); + } + return result; } /** diff --git a/src/test/java/com/annimon/stream/StreamTest.java b/src/test/java/com/annimon/stream/StreamTest.java index 850686e8..aec370aa 100644 --- a/src/test/java/com/annimon/stream/StreamTest.java +++ b/src/test/java/com/annimon/stream/StreamTest.java @@ -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() { + @Override + public Integer apply(Integer length, String s) { + return length + s.length(); + } + }); + assertEquals(10, result); + } + @Test public void testReduceOptional() { Optional result = Stream.ofRange(0, 10) @@ -538,6 +550,25 @@ public void testCollectWithSupplierAndAccumulator() { assertEquals("abcdefg", text); } + @Test + public void testCollect123() { + String string123 = Stream.of("1", "2", "3") + .collect(new Supplier() { + @Override + public StringBuilder get() { + return new StringBuilder(); + } + }, new BiConsumer() { + + @Override + public void accept(StringBuilder value1, String value2) { + value1.append(value2); + } + }) + .toString(); + assertEquals("123", string123); + } + @Test public void testMin() { Optional min = Stream.of(6, 3, 9, 0, -7, 19)