Skip to content

Instantly share code, notes, and snippets.

@hamnis
Last active April 11, 2021 16:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamnis/d4dcac2345ff57415723 to your computer and use it in GitHub Desktop.
Save hamnis/d4dcac2345ff57415723 to your computer and use it in GitHub Desktop.
fold left java
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