user11990861
user11990861

Reputation:

How can I sort array of numbers higher to lower (reverse/decreasing order)?

How can I sort array by numbers higher to lower.

Array

ArrayList<TestClass> array1 = new ArrayList<>();

Class

public class TestClass{

   public boolean type;
   public int counter;

   public TestClass(boolean type, int counter) {
       this.type = type;
       this.counter = counter;
   }
}

I tried do this

Collections.sort(array1);

But I got error

reason: no instance(s) of type variable(s) T exist so that TestClass conforms to Comparable

Upvotes: 2

Views: 421

Answers (2)

Coder
Coder

Reputation: 2239

Assuming you don't have any accessory methods, you can use

array1.sort(Comparator.comparing(a -> a.counter));

The sorting order you asked for is reverse order, there are couple of ways to achieve this.

You can simple do a reverse of the previous sort like

array1.sort(Comparator.comparing(a -> a.counter));
array1.sort(Collections.reverseOrder());

If you can't user Comparator.comparing, you can do as follows

Collections.sort(array1, (item1, item2) -> Integer.compare(item2.counter, item1.counter));

The above statement can be explained as below.

  • Collections.sort() is provided from Java collections framework.

  • First argument specifies which collection needs to be sorted.

  • Second argument depicts on how each object in the collection should be evaluated with other object in comparison. So for every pair of objects, in your case integers here, the condition returns true if the second element is greater than the first one. Which will pull the entire list to appear from higher to lower

Upvotes: 1

Kalpesh Chandora
Kalpesh Chandora

Reputation: 51

arrayList.sort(new Comparator<TestClass>() {
        @Override
        public int compare(TestClass testClass, TestClass t1) {
            return Integer.compare(t1.counter, testClass.counter);
        }
    });

Upvotes: 0

Related Questions