简体   繁体   English

Android:ArrayList的高级比较

[英]Android: advanced compare of ArrayList

I have ArrayList <Integer> a which contains 100 random items [0:100) Items can be repeated. 我有ArrayList <Integer> a ,其中包含100个随机项目[0:100)可以重复的项目。

Also, I have int b = 50 . 另外,我有int b = 50 I want to sort the items in my ArrayList in ascending order of results of this expression: 我想按此表达式结果的升序ArrayList中的项目进行排序:

Math.abs (ArrayList.get(index) - b);

For example: 例如:

65 84 33 18 77... - ArrayList before 65 84 33 18 77... 之前的 ArrayList

15 34 17 32 27 - Math.abs (ArrayList.get(index) - b) before ; 15 34 17 32 27 -Math.abs(ArrayList.get(index)-b) 在之前

65 33 77 18 84... - ArrayList after 65 33 77 18 84... ArrayList 之后

15 17 27 32 34 - Math.abs (ArrayList.get(index) - b) after (in ascending order); 15 17 27 32 34 -Math.abs(ArrayList.get(index)-b) 之后 (按升序排列);

I think, i can do this using java.util.Comparator , but I still don't understand, how it works. 我想,我可以使用java.util.Comparator做到这一点,但我仍然不明白它是如何工作的。 Can someone explait this? 有人可以解释吗? Or, maybe there is another way? 或者,也许还有另一种方法? Thanks! 谢谢!

Yup, you can use a 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);
    }
}

Then plug it into the Collections call: 然后将其插入到Collections调用中:

Collections.sort(a,new MyComparator(50));

This will sort the Integer list according to the criteria in the comparator. 这将根据比较器中的条件对Integer列表进行排序。

Provide a custom Comparator for Collections#sort : 提供Collections#sort的自定义Comparator器:

final int b = ...;
Collections.sort(myList, new Comparator<Integer>() {
        @Override
        public void compareTo(Integer i1, Integer i2) {
             Integer realI1 = (int)Math.abs(i1 - b);
             Integer realI2 = (int)Math.abs(i2 - b);
             return realI1.compareTo(realI2);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM