Java 8 sort on Class member's property

Class declaration:

class Entity {
    String name;
    SubEntity subEntity; // subEntity has a method getAmount() which returns int

I understand with Java 8 we can sort like:


But is there a way I can sort it on sub-entities' properties, for eg:


P.S: All in for any one-liners.


Thanks you for your quick answers but here's something that is not compiling on my intellij 2017.2:

   entities.sort(Comparator.comparing(a -> a.getSubEntity().getAmount()).thenComparing(a -> a.getSubEntity().getAmount()));//This doesnt compile
entities.sort(Comparator.comparing(a -> a.getSubEntity().getAmount())); //This does
Jon Skeet

Not by using a method reference, no - but it's easy to do with a lambda instead:

entities.sort(Comparator.comparing(entity -> entity.getSubEntity().getAmount()));

Fundamentally there's nothing magical about Comparator.comparing - it just accepts a Function<? super T,? extends U> keyExtractor parameter, so you need to work out some way of creating such a function. A method reference is one convenient way of creating a function, but a lambda expression is more flexible one.


See more on this question at Stackoverflow