How to use Comparator.comparing() to compare string as double?

Viewed 1671

I have a List of Accounts and I am trying to use Comparator.comparing to sort them. However, since the balance is string not double, it is sorting incorrectly. Is there a way to sort the balance field in String value as double using Comparator.comparing() ?

It appears to me I have to change the balance type to double to make it work but I am trying not to change do that to keep consistent with other fields all in string type.

List<Account> accountList = getAccountList(id);

Comparator<Account> accountComparator = 
 Comparator.comparing(Account::getBalance);

if (sortDirect.equalsIgnoreCase("desc")) {
    accountList.sort(accountComparator.reversed());
} else {
    accountList.sort(accountComparator);
}

Balance DESC order sorted incorrectly.

"accountList": {      
    "accounts": [
        {
            "accountNumber": "A",
            "balance": "39261.2",
            "payment": "111.42"
        },
        {
            "accountNumber": "B",
            "balance": "251194.28",
            "payment": "128.79"
       ...
    ]

}

1 Answers

You can use a lambda expression to formulate comparison of Double value of the balance string:

Comparator<Account> accountComparator = Comparator.comparingDouble(
        acc -> Double.parseDouble(acc.getBalance()));
Related