简体   繁体   中英

Android: advanced compare of ArrayList

I have ArrayList <Integer> a which contains 100 random items [0:100) Items can be repeated.

Also, I have int b = 50 . I want to sort the items in my ArrayList in ascending order of results of this expression:

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

For example:

65 84 33 18 77... - ArrayList before

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

65 33 77 18 84... - ArrayList after

15 17 27 32 34 - Math.abs (ArrayList.get(index) - b) after (in ascending order);

I think, i can do this using java.util.Comparator , but I still don't understand, how it works. 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.sort(a,new MyComparator(50));

This will sort the Integer list according to the criteria in the comparator.

Provide a custom Comparator for Collections#sort :

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);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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