tags:

views:

75

answers:

2

I have a list of values from 1 to 10, and I want to sort those values in the order 6, 7, 8, 1, 2, 0, 3, 9, 5, 10. How can I sort like this using a comparator?

import java.util.ArrayList;
import java.util.List;

public class SortTest {
 public static void main(String[] args) {
  int a[] = { 6, 7, 8, 1, 2, 0, 3, 9, 4, 5, 10 };
  List list1 = new ArrayList(20);
  List list = new ArrayList(20);
  list.add(0);
  list.add(1);
  list.add(2);
  list.add(3);
  list.add(4);
  list.add(5);
  list.add(6);
  list.add(7);
  list.add(8);
  list.add(9);
  list.add(10);

  for (int i = 0; i < a.length; i++) {
   for (int j = 0; j < list.size(); j++) {
    if (a[i] == (Integer) list.get(j)) {
     list1.add(list.get(j));
    }
   }
  }

  System.out.println(list1);
 }
}
+2  A: 

You need to make a new class which implements the Comparator interface and provides a compareTo() method which returns -1, 0, or 1 according to your sorting rules. Then use Collections.sort(myList, myComparator);.

If you post the rule logic, we can be more help. If your logic is literally "given the integers 1 through 10, return 6,7,8,1,2,0,3,9,5,10" then the comparator would be:

public class InterestingComparator implements Comparator<Integer> {
    private static final List<Integer> myOrder = Arrays.toList({6,7,8,1,2,0,3,9,5,10});

    public int compare(Object arg0, Object arg1) {
        if ((arg0 instanceof Integer) && (arg1 instanceof Integer)) {
            int int0 = (Integer) arg0;
            int int1 = (Integer) arg1;
            if ((myOrder.contains(int0)) && (myOrder.contains(int1))) {
                /** Both items are "valid" i.e. present in the list */
                return myOrder.indexOf(int0).compareTo(myOrder.indexOf(int1));
            } else {
                /** default to the current order */
                return -1;
            }
        } else {
            throw new IllegalArgumentException("Either arg0 or arg1 is not an Integer.");
        }
    }
}

Note: This was written on a machine that doesn't have Java, so there may be some syntax errors. That is not an excuse for possible mental errors.

Andy
A: 

(update moved into question, please delete this "answer")

Rakesh
Do not post updates, comments or questions as **answers**. The box at the bottom is to post an *answer*. If you want add an update to your question, use the `edit` link below the question. If you want to post a comment, use the `add comment` link below the question or answer you'd like to (reply) comment on.
BalusC