Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iterator.takeWhile() #487 #511

Merged
merged 1 commit into from
Aug 25, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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