1

Possible Duplicate:
Sorting a collection of objects

How to sort the list in java

List<Integer> list = new ArrayList<Integer>();
list.add(13);
list.add(8);
list.add(6);
list.add(4);
list.add(3);

i want to sort the list. Please help me to solve this.

Community
  • 1
  • 1
Srivathsan
  • 519
  • 4
  • 18

4 Answers4

1

You can use Collections.sort(list), but note that your list must be made of objects that implement Comparable to use this! http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html

Zavior
  • 6,412
  • 2
  • 29
  • 38
1

This link should help. It's an example for String list, but it should be working for integers too. Must say, I didn't try it myself.

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
1

just use:

 Collections.sort(list);

if you want to sort in reverse order you have to implement the Comparator interface

public class MyIntComparable implements Comparator<Integer>{

    @Override
    public int compare(Integer o1, Integer o2) {
        return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
    }
}

and in your code use:

Collections.sort(list, new MyIntComparable());
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
0
List<Integer> list = new ArrayList<Integer>();
list.add(13);
list.add(8);
list.add(6);
list.add(4);
list.add(3);
Collections.sort(list);
Jonathon Faust
  • 12,396
  • 4
  • 50
  • 63