Java arraylist sort


 

Java arraylist sort

This Java Tutorial section we demonstrates how to use the sort() method in the Java ArrayList.

This Java Tutorial section we demonstrates how to use the sort() method in the Java ArrayList.

  • ArrayList doesn't have sort() method.
  • We can use the static sort  method of the Collections class
  • It sorts the given Collection object.


Example of Java Arraylist Sort
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class List1 {
    public static void main(String[] args) {
     Integer ar[]={444,222,333,111};
     ArrayList list=new ArrayList();
     list.add(ar[0]);
     list.add(ar[1]);
     list.add(ar[2]);
     list.add(ar[3]);
     System.out.println("Withiout sorting "+list);
     Collections.sort(list);
     System.out.println("After sorting "+list);
  }
}

Output
Withiout sorting [444, 222, 333, 111]
After sorting [111, 222, 333, 444]

Ads