سؤال

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?

هل كانت مفيدة؟

المحلول

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));

نصائح أخرى

Use this to sort in descending order -

Collections.sort(data, Collections.reverseOrder(aStringComparator));

Try this:

    Collections.sort(data, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            int n1 = Integer.parseInt(s1.substring(1));
            int n2 = Integer.parseInt(s2.substring(1));
            return Integer.compare(n2, n1);
        }});

def Descending_Order(num): > # num = 18902

l = list(map(int, str(num)))            >  # [1, 8, 9, 0, 2]

r = sorted(l,reverse=True)              > # [9, 8, 2, 1, 0]

ch_r = map(str, r)                      > # ['9', '8', '2', '1','0']

num_r =''.join(ch_r)                    > # '98210'

return int(num_r)                       > # 98210
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top