Skip to content

Commit

Permalink
Iterator.takeWhile() #487
Browse files Browse the repository at this point in the history
  • Loading branch information
ruslansennov committed Aug 25, 2015
1 parent c3c3e25 commit c6116b4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/main/java/javaslang/collection/HashSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -446,8 +446,8 @@ public HashSet<T> takeRight(int n) {
@Override
public HashSet<T> takeWhile(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
List<T> taken = list.get().takeWhile(predicate);
return taken.length() == list.get().length() ? this : HashSet.ofAll(taken);
HashSet<T> taken = HashSet.ofAll(iterator().takeWhile(predicate));
return taken.length() == length() ? this : taken;
}

@Override
Expand Down
30 changes: 29 additions & 1 deletion src/main/java/javaslang/collection/Iterator.java
Original file line number Diff line number Diff line change
Expand Up @@ -727,7 +727,35 @@ default Iterator<T> takeRight(int n) {
@Override
default Iterator<T> takeWhile(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return null;
final Iterator<T> that = this;
return new Iterator<T>() {

private T next = null;
private boolean finished = false;

@Override
public boolean hasNext() {
while (!finished && next == null && that.hasNext()) {
final T value = that.next();
if (predicate.test(value)) {
next = value;
} else {
finished = true;
}
}
return next != null;
}

@Override
public T next() {
if (!hasNext()) {
EMPTY.next();
}
final T result = next;
next = null;
return result;
}
};
}

default <U> Iterator<Tuple2<T, U>> zip(Iterable<U> that) {
Expand Down

0 comments on commit c6116b4

Please sign in to comment.