Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the string number in descending order?

Below is my list which will always be in the form of bXXXX -

List<String> data = Arrays.asList("b5", "b10", "b2", "b1", "b40");
System.out.println(data);

My data list will always have strings in the form of bXXXX

Now I need to sort my above lists in descending order and extract the largest string from it..

So in the above example, it will be b40.. So below is the comparator I am using which sorts everything in ascending order -

static final Comparator<String> aStringComparator = new Comparator<String>() {
    public int compare(String s1, String s2) {
        //assumed input are strings in the form axxxx
        int numfromS1 = Integer.valueOf(s1.subSequence(1, s1.length()).toString());
        int numfromS2 = Integer.valueOf(s2.subSequence(1, s2.length()).toString());
        return numfromS1 - numfromS2;
    }
};

And I am not able to understand how do I make this to sort it out in descending order so that I can extract the first index from the list which will be greatest string number?


1 Answers

If your comparator works in ascending order, then all you need to do is to invert the result of your comparator.

If this code works for you:

return numfromS1 - numfromS2;

then change it to:

return numfromS2 - numfromS1;

or, maybe to the little more idiomatic:

return (numfromS2 < numfromS1) ? -1: (numfromS2 > numfromS1) ? 1 : 0;

and now your data is going to be in descending order.

You could also, as suggested by others, use either:

return ((Integer) numfromS2).compareTo(numfromS1);

or:

Collections.sort(data, Collections.reverseOrder(aStringComparator));
like image 65
TacticalCoder Avatar answered Sep 07 '25 21:09

TacticalCoder