Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a Java list using two different values?

Tags:

java

sorting

public void sortLeagueTable(List<LeagueTableItem> table) {
    Collections.sort(table, new Comparator<LeagueTableItem>(){
        public int compare(LeagueTableItem o1, LeagueTableItem o2){
            return o2.getPoints() - o1.getPoints();
        }
    });
}

This code sorts two lists based on the value of the object called points. After I sort it based on the value point I want to sort it again based on the value goalScored. So, if the points of two teams are equal, I want to sort it again based on the goalScored value.

How can I do that?

like image 432
Dawn17 Avatar asked Jun 22 '26 04:06

Dawn17


1 Answers

Java 8's enhancements to the Comparator interface give you a pretty elegant way of achieving this:

table.sort(Comparator.comparingInt(LeagueTableItem::getPoints)
                     .thenComparingInt(LeagueTableItem::goalScored));
like image 200
Mureinik Avatar answered Jun 23 '26 17:06

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!