For review -- Comparator combinators

Brian Goetz brian.goetz at oracle.com
Tue Nov 13 20:47:47 PST 2012


>> The following is a webrev for proposed extension methods on Comparator
>> (reverse and compose) as well as static combinator methods in
>> Comparators for things like turning a T -> {Comparable,int,long,double}
>> into a Comparator<T>.
>>
>>    http://cr.openjdk.java.net/~henryjen/webrevs/8001667.0/
>>
>> This allows things like:
>>
>>    people.sort(Comparators.comparing(Person::getName))
>>
>>    Comparator<Person> byLastFirst
>>        = Comparators.comparing(Person::getLastName)
>>                     .compose(Comparators.comparing(Person::getFirstName))
>>
>> Please review and comment.
>
> I like the .compose notion in general, but wouldn't it be nice if you
> could also, as a special case, do something like this:
>
> Comparitor<Person> byLastFirst =
> Comparators.comparing(Person::getLastName, Person::getFirstName);

Its a nice idea, but it has one kind of nasty limitation -- you can't 
mix an int-extractor with a Comparable-extractor because there's no 
common supertype of Function<T, U extends Comparable> and IntFunction. 
So this would fail with

   Comparators.comparting(Person::getLastName, Person::getHeight)

for reasons that would probably surprise many users.  (Also varargs may 
interact less than ideally with lambda and type inference, but maybe not.)

> Or at least:
>
> Comparitor<Person> byLastFirst =
> Comparators.comparing(Person::getLastName).compose(Person::getFirstName);

Yes, we could overload Comparator.compose(Comparator) with

   compose(Function<T, U extends Comparable>)
   compose(IntFunction<T>)
   compose(LongFunction<T>)



More information about the lambda-libs-spec-observers mailing list