Sunday, May 2, 2010

Sorting a list in java using comparator

[sourcecode language="css"]
public class SortTest {
    public static void main(String[] args) {
        List<Integer> ls = new ArrayList<Integer>();
        for (int i = 1; i &lt; 10; i++) {
            Random r = new Random();
            int randomNo = r.nextInt(i);
            ls.add(randomNo);
        }
        System.out.println("before sorting:" + ls);
        Comparator c = new Comparator() {
            @Override
            public int compare(Object arg0, Object arg1) {
                if ((Integer) arg0 &gt; (Integer) arg1) {
                    return 1;
                } else if ((Integer) arg0 == (Integer) arg1) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };
        Collections.sort(ls, c);
        System.out.println("after sorting:" + ls);

    }
}
[/sourcecode]

No comments:

Post a Comment