Java 8 sort on Class member's property

Sachin Verma :

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.

Andrew Tobilko :

Guys gave you good answers. It isn't supposed to be an improvement over their answers. I just want to provide an alternative idea.

entities.sort(Comparator.comparing(((Function<Entity, SubEntity>)Entity::getSubEntity).andThen(SubEntity::getAmount)));

I formed a key extractor by combining two functions Entity::getSubEntity and SubEntity::getAmount with Function#andThen. Both have been written as method references. The cast is required to determine the type of an instance and call andThen on that instance.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=458659&siteId=1