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:

entities.sort(Comparator.comparing(Entity::name));

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

entities.sort(Comparator.comparing(Entity::SubEntity::getAmount()));

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

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow