In this post under Java, I will show with example how to sort a list.
Below is the complete main class for your reference
Main class
1 package core.collection;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6
7 public class SortingList {
8 public static void main(String []args) {
9 List<Integer> integerList = new ArrayList<>(0);
10 integerList.add(5);
11 integerList.add(2);
12 integerList.add(6);
13 integerList.add(1);
14 integerList.add(4);
15 integerList.add(3);
16
17 System.out.println("Before sorting: " + integerList);
18
19 Collections.sort(integerList);
20
21 System.out.println("After sorting: " + integerList);
22 }
23 }
In the above code, at line 9 I created list of type parameter Integer named “integerList” and populated it.
Then at line 19, I use “Collections” class “sort” method to sort the list. This method takes a list as an argument.
This “sort” method sorts the elements using natural order that means, the element type which in this case is Integer should have already implemented “Comparable” interface.
Then only the collection elements are property sorted.
In this way we can sort a list.