Collections sort
compare must return int when override For example, we define a new class
Book
- Use lambda expression
Collections.sort(listBooks, (b1, b2) -> (int) (b1.getPrice() - b2.getPrice()));
- Create new comparator for
Bookclass
class SortbyPrice implements Comparator<Book>
{
public int compare(Book b1, Book b2) {
return (int)(b1.getPrice() - b2.getPrice());
}
}
Collections.sort(listBooks, new SortbyPrice());
- Use inner class of Comparator
Collections.sort(listBooks, new Comparactor<>(){
@Override
public int compare(Book b1, Book b2) {
return (int)(b1.getPrice() - b2.getPrice());
}
});