1

I have this Java 8 code:

Contact contact = new Contact("");
for (ContactEvent event : events) {
    contact = contact.apply(event);
}

and I want to transform it to be functional using Stream.reduce method. I have tried this:

Contact contact = events.stream()
    .reduce(new Contact(""), 
    (contact1, contactEvent) -> contact1.apply(contactEvent), //Ok!
    (contact12, contact2) -> null); //I don't want this!

Why do I have to combine two Contacts? What am I supposed to do in the combiner?

If I return null, like above, it works fine. And debugger does not even execute that line (return null).

Héctor
  • 24,444
  • 35
  • 132
  • 243

1 Answers1

2

The matter of fact is you cannot avoid the combiner function in this specific case.

However, it's worth mentioning that the combiner function (contact12, contact2) -> null will not be called at all. in order for a combiner to work, a stream must be parallel. Otherwise, just the accumulator function will be called.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 1
    Why can't the combiner be avoided? – Carcigenicate Jun 15 '18 at 14:44
  • 2
    @Carcigenicate because the only other overload of the reduce `T reduce​(T identity, BinaryOperator accumulator)` can only operate on elements of the same type. `events` is of type `ContactEvent` and the identity value is of type `Contact`. So, you're _forced_ to use this ` U reduce​(U identity, BiFunction accumulator, BinaryOperator combiner)` overload in this specific case. – Ousmane D. Jun 15 '18 at 14:48
  • @Aominè yes, you are right! Thank you. IMHO this is a bad API design... isn't it? – Héctor Jun 15 '18 at 14:50
  • 1
    @Aominè Ahh, I see. That's quite the odd design decision on the author's part. Normally, the reducing function takes an argument with the same type as the accumulator, and the second as the same type as the collection elements. Unless there's a Stream nuance forcing that. – Carcigenicate Jun 15 '18 at 14:51
  • @Héctor You might find this answer from [Stuart Marks on the need for the additional combiner function](https://stackoverflow.com/questions/24308146/why-is-a-combiner-needed-for-reduce-method-that-converts-type-in-java-8/24316429#24316429) of interest to you. – Ousmane D. Jun 15 '18 at 15:14