Created
April 10, 2016 21:20
-
-
Save nbardiuk/142a43f5a4a6ee88417f60622fa9a62c to your computer and use it in GitHub Desktop.
foldLeft with early termination for javaslang stream
This file contains 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
import javaslang.collection.Stream; | |
import java.util.function.BiFunction; | |
import java.util.function.Predicate; | |
public class FoldLeftTermination { | |
public static void main(String[] args) { | |
Stream<Integer> numbers = Stream.iterate(0, i -> i + 1) | |
.peek(System.out::println) // track consumed numbers | |
.take(10000); | |
Integer sum = foldLeftWithTermination(numbers, | |
0, | |
(s, i) -> s + i, | |
s -> s < 10); | |
System.out.println("Sum " + sum); | |
//OUTPUT: | |
//0 | |
//1 | |
//2 | |
//3 | |
//4 | |
//Sum 6 | |
} | |
static <S, A> S foldLeftWithTermination(Stream<A> stream, | |
S zero, | |
BiFunction<S, A, S> biFunction, | |
Predicate<S> predicate) { | |
return stream | |
.scanLeft(zero, biFunction) | |
.takeWhile(predicate) | |
.last(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment