diff --git a/stream/src/main/java/com/annimon/stream/Stream.java b/stream/src/main/java/com/annimon/stream/Stream.java index 659244b3..f84fb629 100644 --- a/stream/src/main/java/com/annimon/stream/Stream.java +++ b/stream/src/main/java/com/annimon/stream/Stream.java @@ -12,6 +12,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Queue; import java.util.Set; @@ -472,10 +473,33 @@ public R custom(Function, R> function) { * @return the new stream */ public Stream filter(final Predicate predicate) { - return new Stream(new LsaExtIterator() { + return new Stream(new Iterator() { + + private boolean hasNext, hasNextEvaluated; + private T next; @Override - protected void nextIteration() { + public boolean hasNext() { + if (!hasNextEvaluated) { + nextIteration(); + hasNextEvaluated = true; + } + return hasNext; + } + + @Override + public T next() { + if (!hasNextEvaluated) { + hasNext = hasNext(); + } + if (!hasNext) { + throw new NoSuchElementException(); + } + hasNextEvaluated = false; + return next; + } + + private void nextIteration() { while (iterator.hasNext()) { next = iterator.next(); if (predicate.test(next)) { diff --git a/stream/src/test/java/com/annimon/stream/StreamTest.java b/stream/src/test/java/com/annimon/stream/StreamTest.java index f0bf5c72..19858f86 100644 --- a/stream/src/test/java/com/annimon/stream/StreamTest.java +++ b/stream/src/test/java/com/annimon/stream/StreamTest.java @@ -199,6 +199,26 @@ public BigInteger apply(BigInteger value1, BigInteger value2) { assertEquals(new BigInteger("1267650600228229401496703205375"), sum); } + @Test(timeout=2000) + public void testIterateIssue53() { + Optional res = Stream + .iterate(0, new UnaryOperator() { + @Override + public Integer apply(Integer value) { + return value + 1; + } + }) + .filter(new Predicate() { + @Override + public boolean test(Integer value) { + return value == 0; + } + }) + .findFirst(); + assertThat(res, isPresent()); + assertThat(res.get(), is(0)); + } + @Test public void testConcat() { final PrintConsumer consumer = new PrintConsumer();