Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator using a double in Java

This code

public class MyComparatorWinPCT implements Comparator<Team> {

@Override
public int compare(Team o1, Team o2) {
    // TODO Auto-generated method stub
    if(o1.rWinPCT > o2.rWinPCT)
    {
        return -1;
    }
    if(o1.rWinPCT < o2.rWinPCT)
    {
        return 0;
    }

    return 1;
 }

}

Produces this output.

Houston Rockets, 1, 0.793

Golden State Warriors, 2, 0.707

Atlanta Hawks, 3, 0.293

Oklahoma City Thunder, 4, 0.585

Here is how the method is invoked.

Collections.sort(teams, new MyComparatorWinPCT());

Win percentage is being used to compare and it's a double. I've tried every combo of the return statements but can't get it right. I need it in descending order based on win percentage. The highest win percentage first, then so on.

like image 508
Jason Avatar asked Dec 17 '22 19:12

Jason


1 Answers

You may do following changes in your code:

public int compare(Team o1, Team o2) {
    return Double.compare(o1.rWinPCT, o2.rWinPCT);
}
like image 169
BishalG Avatar answered Jan 01 '23 09:01

BishalG