On 02/22/2016 11:06 AM, Tagir Valeev wrote:
Hello!

Consider the following code:

Comparator<String> cmp = Comparator.nullsFirst(Comparator.naturalOrder());
System.out.println(Stream.of("a", "b",
null).collect(Collectors.minBy(cmp)));

It prints Optional.empty, so the result is indistinguishable from empty
Stream (siimlar for maxBy). This behavior is not consistent with
Stream.findFirst() (which throws NPE if the resulting element is null).
Currently minBy spec says:

This produces a result equivalent to:
      reducing(BinaryOperator.minBy(comparator))

However reducing spec says nothing what will occur if the result of
reduction is null. To my opinion at very least the spec of reducing should
be updated to specify the behavior when reducing result is null. It
probably would also be nice to add a note into minBy/maxBy spec about this.

What do you think?

My personal opinion is that it would be better to throw NPE in this case (like with findFirst()). Silently converting null element to Optional.empty() is probably not the desired behavior and I doubt anyone is exploiting this implementation detail in such way.

Regards, Peter


With best regards,
Tagir Valeev.

Reply via email to