This question is targeted to Vavr (Java's FP library), but could probably apply to Scala or other FP languages that can compare to Java.
What's the difference between Vavr foldLeft
:
-
<U> U foldLeft(U zero, BiFunction<? super U, ? super T, ? extends U> combiner)
and Java's collect
:
-
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)
It seems both can achieve the same purpose: Transform a collection (say Stream<T>
) by traversing it and accumulating a result into a new type U
(or R
) while traversing.
At first sight, signatures differ in #arguments, and Java collect
seems to be intended to be run in parallel chunks.
Which are the actual differences conceptually? Vavr foldLeft
seems easier to use.
Very dumb example just to illustrate:
Vavr foldLeft
:
// result = "HelloFunctionalWorld"
String result = Seq("Hello", "Functional", "World")
.foldLeft(new StringBuilder(), (acc, word) -> acc.append(word))
.toString();
Java collect
:
// result = "HelloFunctionalWorld"
final String result = Arrays.asList("Hello", "Functional", "World").stream()
.collect(
StringBuilder::new,
(acc, word) -> acc.append(word),
StringBuilder::append
)
.toString();