我有ArrayList <Integer> a
其中包含 100 个随机项目 [0:100) 项目可以重复。
另外,我有 int b = 50
.我想按此表达式结果的升序顺序对我的ArrayList 中的项目进行排序:
Math.abs (ArrayList.get(index) - b);
例如:
65 84 33 18 77...
- ArrayList 之前
15 34 17 32 27
- Math.abs (ArrayList.get(index) - b) 之前;
65 33 77 18 84...
- ArrayList 之后
15 17 27 32 34
- Math.abs (ArrayList.get(index) - b) after(升序);
我想,我可以使用 java.util.Comparator 来做到这一点,但我仍然不明白它是如何工作的。有人可以解释一下吗?或者,也许还有另一种方法?谢谢!
最佳答案
是的,您可以使用比较器。
class MyComparator implements Comparator<Integer> {
private final int b;
public MyComparator(int b) { this.b = b; }
public int compare(Integer o1, Integer o2) {
Integer i1 = Math.abs(o1 - b);
Integer i2 = Math.abs(o2 - b);
return i1.compareTo(i2);
}
}
然后将其插入到 Collections 调用中:
Collections.sort(a,new MyComparator(50));
这将根据比较器中的标准对 Integer
列表进行排序。
关于java - Android:ArrayList 的高级比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23762978/