Salman9
Salman9

Reputation: 265

sort a list on strings based on a double value in java

I have a list of strings in the following format

["BlahBlahBlahBlah   0.9877"]
["ABCabcABCabcAbc   1.7852"]

As you can see between the two is a single space. I cannot change the design due to some restrictions.

What I need to do is to sort the list based on the double number at the end. Can anyone help me implement this code?

Upvotes: 0

Views: 1955

Answers (2)

Boann
Boann

Reputation: 50021

That's not a single space, but anyway...

Collections.sort(yourList, new Comparator<String>() {
    public int compare(String s1, String s2) {
        double d1 = Double.valueOf(s1.substring(s1.lastIndexOf(' ') + 1));
        double d2 = Double.valueOf(s2.substring(s2.lastIndexOf(' ') + 1));
        return Double.compare(d1, d2);
    }
});

(import java.util.Collections and java.util.Comparator if not already.)

Upvotes: 3

Embattled Swag
Embattled Swag

Reputation: 1469

If you know for a fact that the number will always be the format X.XXXX (five digits and a decimal), you can do something like '

String asString = yourString.substring(yourString.length-9,yourString.length-3);
Double asDouble = Double.parseDouble(number);

Upvotes: 0

Related Questions