简体   繁体   中英

Sorting Array according to ArrayList using comparator

I'm trying to sort an Array (Object hits[]) that stores Objects and I need to be sorted with the exact order (asceding, descending) as in ArrayList which is already sorted. These two are not related in any way.

I have seen similar problems, with the difference that you sort the ArrayList using the order in the Array. But I want the opposite. I tried to convert the ArrayList to simple Array and go from there, so the problem becomes "sorting array using another array" but that didn't really helped me since I want "sorting array of Objects using another array".

Arrays.sort(hits, new Comparator<ArrayList<Double>>() {
        @Override
        public int compare(ArrayList<Double> c1, ArrayList<Double> c2) {
              return Double.compare(c1.get(0), c2.get(0));
        }
    });

I want something in the vein of the code above, which is giving me the error "not applicable" with the types I'm currently using as arguments.

A Comparator is not defined in terms of the Collection is going to operate over; but in terms of the elements is going to operate on.

So, your Comparator needs to be something like Comparator<Double> rather than Comparator<ArrayList<Double>> , then you can use it to sort any Collection including arrays indistinctly.

The following is a working demo of how a the SAME Comparator is used indistinctly to sort a List of custom objects and also to sort an array of the same custom objects:

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class SortArrayLists {

    public static void main(String[] args) {
        Comparator<MyObject> comparator = Comparator.comparingDouble(MyObject::getDoubleValue);     

        MyObject[] array = new MyObject[] {
                new MyObject(55),
                new MyObject(17.3),
                new MyObject(2.43),
                new MyObject(375),
                new MyObject(100),
                new MyObject(255)
        };
        List<MyObject> list = Arrays.asList(array);
        list.sort(comparator);
        Arrays.sort(array, comparator);

        list.stream().forEach(System.out::println);
        System.out.println("\n\n");
        Arrays.stream(array).forEach(System.out::println);
    }

    static class MyObject {
        private double doubleValue;

        public MyObject(double doubleValue) {
            this.doubleValue = doubleValue;
        }

        public double getDoubleValue() {
            return doubleValue;
        }

        public String toString() {
            return doubleValue + "";
        }
    }
}

Complete code on GitHub

Hope this helps.

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