Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
       ...
    ]

}

like image 649
user1747980 Avatar asked Jun 14 '19 03:06

user1747980


People also ask

How can you compare strings using the Compare () method?

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.

How does Comparator compare work?

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.

Can we use compareTo in Comparator?

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.


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()));
like image 106
Naman Avatar answered Sep 28 '22 06:09

Naman