Last active
August 29, 2015 14:08
-
-
Save danieldietrich/a6cbe1ed5270c4aa8967 to your computer and use it in GitHub Desktop.
Use javaslang.Option instead of java.util.Optional if null is permitted
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| The `Option` next is used to test if the iterator has more elements. | |
| In particular the value of `new Some<>(iterator.next())` is always present, even if `iterator.next()` is null. | |
| This would not be possible with `Optional.of(iterator.next())`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** / \____ _ ______ _____ / \____ ____ _____ | |
| * / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang | |
| * _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014 Daniel Dietrich | |
| * /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0 | |
| */ | |
| package javaslang.collection; | |
| import java.util.Iterator; | |
| import java.util.NoSuchElementException; | |
| import java.util.function.Predicate; | |
| import javaslang.monad.None; | |
| import javaslang.monad.Option; | |
| import javaslang.monad.Some; | |
| public final class Iterators { | |
| private Iterators() { | |
| throw new AssertionError(Iterators.class.getName() + " is not intended to be instatiated."); | |
| } | |
| public static <T> Iterator<T> of(Iterator<T> iterator, Predicate<? super T> whileCondition) { | |
| return new Iterator<T>() { | |
| Option<T> next = testNext(); | |
| @Override | |
| public boolean hasNext() { | |
| return next.isPresent(); | |
| } | |
| @Override | |
| public T next() { | |
| final T result = next.orElseThrow(() -> new NoSuchElementException("no more elements")); | |
| next = testNext(); | |
| return result; | |
| } | |
| Option<T> testNext() { | |
| return (iterator.hasNext() ? new Some<>(iterator.next()) : None.<T> instance()) | |
| .filter(whileCondition); | |
| } | |
| }; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment