如何按数字从高到低对数组进行排序。
数组
ArrayList<TestClass> array1 = new ArrayList<>();
类
public class TestClass{
public boolean type;
public int counter;
public TestClass(boolean type, int counter) {
this.type = type;
this.counter = counter;
}
}
我试过这样做
Collections.sort(array1);
但是我得到了错误
reason: no instance(s) of type variable(s) T exist so that TestClass conforms to Comparable
最佳答案
假设你没有任何辅助方法,你可以使用
array1.sort(Comparator.comparing(a -> a.counter));
您要求的排序顺序是倒序,有两种方法可以实现。
你可以简单地做与之前排序相反的事情
array1.sort(Comparator.comparing(a -> a.counter));
array1.sort(Collections.reverseOrder());
如果你不能使用Comparator.comparing
,你可以这样做
Collections.sort(array1, (item1, item2) -> Integer.compare(item2.counter, item1.counter));
上述说法可以解释如下。
Collections.sort()
由Java 集合框架
提供。第一个参数指定需要排序的集合。
- 第二个参数描述集合中的每个对象应该如何 与其他对象进行比较来评价。因此,对于每一对对象,在您的情况下为整数,如果第二个元素大于第一个元素,则条件返回 true。这将使整个列表从高到低出现
关于android - 如何将数字数组从高到低排序(倒序/降序)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57698867/