Comparators.comparing doesn't handle nulls

Michael Hixson michael.hixson at
Thu Apr 18 16:40:41 PDT 2013

I believe he is talking about handling nulls within, b).  At the risk of beating a dead horse, I'll
repeat something I suggested in the past.  Either (A) or (B) below:

A) Extension methods on Comparator, like Guava:

  default <S extends T> Comparator<S> nullsFirst() { ... }
  default <S extends T> Comparator<S> nullsLast() { ... }

B) Static methods on Comparators:

  public static Comparator<Object> nullsFirst() { ... }
  public static Comparator<Object> nullsLast() { ... }

The first form would be easier to implement.  The methods would return
a modified version of the current comparator that permits null
arguments to compare(a, b).

The second form would be slightly harder to implement (~100 or so
lines of code IIRC).  The methods would return singletons that permit
null arguments to compare(a, b).  These singletons will have
overridden implementations of whatever methods necessary to preserve
null-safety throughout further chained calls to thenComparing(...)
methods.  For example:

  // Compare strings with nulls first and the rest in case-insensitive order.
  Comparator<String> c = Comparators.nullsFirst()


I personally prefer the second form (B).


On Thu, Apr 18, 2013 at 3:50 PM, Henry Jen <henry.jen at> wrote:
> Would you be more specific?
> Comparators.comparing is not taking null as arguments. As how the returned Comparator compare nulls is really depends on Comparator itself. The Comparable style comparator won't handle null as Comparable doesn't support null.
> Cheers,
> Henry
> On Apr 18, 2013, at 1:28 PM, Michael Nascimento <misterm at> wrote:
>> Hi guys,
>> In most usages of Guava's ComparisonChain / Ordering that I am trying
>> to replace with Comparator, nulls are involved. Comparators.comparing
>> provides no easy way of handling this except by writing verbose code.
>> Any plans to improve on that?
>> Regards,
>> Michael

More information about the lambda-dev mailing list