Reputation:
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
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.
Upvotes: 1
Reputation: 51
arrayList.sort(new Comparator<TestClass>() {
@Override
public int compare(TestClass testClass, TestClass t1) {
return Integer.compare(t1.counter, testClass.counter);
}
});
Upvotes: 0