Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by comparable Bean property in Java 8

Tags:

java

Is there a shorter way to sort by a comparable property using Java 8 streams than this pattern?

collection.stream()
    .sorted((a,b) -> a.getProp().compareTo(b.getProp()))
like image 450
Timo Westkämper Avatar asked Mar 20 '23 13:03

Timo Westkämper


1 Answers

Yes, you could use method reference for this:

collection.stream().sorted(Comparator.comparing(MyClass::getProp));
like image 155
Alexis C. Avatar answered Apr 02 '23 07:04

Alexis C.