Is there a concise way to create a <X> comparator based on X.getY () ordering

Is there a shorter way to say this:

final Comparator<ClassA> byName = 
    (final ClassA a1, final ClassA a2) 
        -> a1.getName().compareTo( a2.getName() ));

      

I know getName () will never return null.

Perhaps something along these lines is using a method reference:

final Comparator<ClassA> byName = ????( ClassA::getName );

      

+3


source to share


1 answer


you can shorten it to:



final Comparator<ClassA> byName =
                Comparator.comparing(ClassA::getName);

      

+5


source







All Articles