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"
...
]
}
The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. That is all there is to this. When you write a Comparator, you define what order you want.
In Java, we can implement whatever sorting algorithm we want with any type. Using the Comparable interface and compareTo() method, we can sort using alphabetical order, String length, reverse alphabetical order, or numbers. The Comparator interface allows us to do the same but in a more flexible way.
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With