Comparators.comparing doesn't handle nulls

Michael Nascimento misterm at gmail.com
Thu Apr 18 18:12:48 PDT 2013


Yes, Michael, that's precisely what I was referring to and I agree
with your suggestions.

Regards,
Michael

On Thu, Apr 18, 2013 at 8:40 PM, Michael Hixson
<michael.hixson at gmail.com> wrote:
> I believe he is talking about handling nulls within
> Comparator.compare(a, 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()
>
> .thenComparing(String.CASE_INSENSITIVE_ORDER);
>
> I personally prefer the second form (B).
>
> -Michael
>
> On Thu, Apr 18, 2013 at 3:50 PM, Henry Jen <henry.jen at oracle.com> 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 gmail.com> 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