Skip to content

Instantly share code, notes, and snippets.

@nbardiuk
Created April 10, 2016 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbardiuk/142a43f5a4a6ee88417f60622fa9a62c to your computer and use it in GitHub Desktop.
Save nbardiuk/142a43f5a4a6ee88417f60622fa9a62c to your computer and use it in GitHub Desktop.
foldLeft with early termination for javaslang stream
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