How to sort a list in Java:
In this Java programming tutorial, we will learn how to sort a list . The program will sort the list and print it out again .
Let’s have a look at the program first :
Java program :
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
//1
private static void printList(List list){
for(String item : list){
System.out.print(item+" ");
}
}
public static void main(String[] args){
//2
List items = new ArrayList<>();
//3
items.add("d");
items.add("c");
items.add("b");
items.add("a");
//4
System.out.println("Items before sorted : ");
printList(items);
//5
Collections.sort(items);
//6
System.out.println("\nItems after sorted : ");
printList(items);
}
}
Explanation :
The commented numbers in the above program denote the step numbers below :
-
The function printList is used to print a list. It will take one List as input and print out its elements.
-
Create one ArrayList that can hold strings.
-
Add few characters to the list.
-
Print out the list content to the user.
-
Now,sort the list using the sort method of the Collections class.
-
Finally print out the contents of the sorted list.
Sample Output:
Items before sorted :
d c b a
Items after sorted :
a b c d