Ozan
Ozan

Reputation: 1401

sorting specific elements in list using Comparator

In Java, using comparator, is it possible to sort elements at the specific positions in a list? If so, how? Example : the list {1,2,3,4,10,6,7,8} indices of elements to be sorted {3,4,7} in descending order, the result would be {1,2,3,10,8,6,7,4}.

Upvotes: 1

Views: 519

Answers (2)

Alex
Alex

Reputation: 827

Would something like this work? You would construct the Comparator with a list of the values and the list of indexes to sort:

private static class MyComparator implements Comparator<Integer>{

        private ArrayList<Integer> indexes;
        private ArrayList<Integer> vals;
        public MyComparator(ArrayList<Integer> indexes, ArrayList<Integer> vals){
            this.indexes = indexes;
            this.vals = vals;
        }
        @Override
        public int compare(Integer arg0, Integer arg1) {

            if(indexes.contains(vals.indexOf(arg0)) && indexes.contains(vals.indexOf(arg1))){
                return Integer.compare(arg1, arg0); 
            }
            return 0;
        }

    }

Upvotes: 0

Software2
Software2

Reputation: 2738

Presumably you know the specific positions beforehand? If so, create a new list comprised of the elements you want to sort, sort the list, and then replace the elements in the original list with your sorted list, one element at a time.

Upvotes: 1

Related Questions