Last active
April 11, 2021 16:40
-
-
Save hamnis/d4dcac2345ff57415723 to your computer and use it in GitHub Desktop.
fold left java
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
public static <A, B> B foldLeft(Stream<A> iterable, B identity, BiFunction<B, A, B> bf) { | |
return foldLeft(iterable.iterator(), identity, bf); | |
} | |
public static <A, B> B foldLeft(Iterable<A> iterable, B identity, BiFunction<B, A, B> bf) { | |
return foldLeft(iterable.iterator(), identity, bf); | |
} | |
public static <A, B> B foldLeft(Iterator<A> iterator, B identity, BiFunction<B, A, B> bf) { | |
B result = identity; | |
while(iterator.hasNext()) { | |
A next = iterator.next(); | |
result = bf.apply(result, next); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment