1. Introduction
Sorting a List in Java can be performed using various methods, but one of the most straightforward ones is using the Collections.sort() method. This method sorts the specified List into ascending order, according to the natural ordering of its elements or by a specified comparator.
2. Program Steps
1. Create a List of integers.
2. Print the original List.
3. Use the Collections.sort() method to sort the List.
4. Print the sorted List.
3. Code Program
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class SortList {
public static void main(String[] args) {
// Step 1: Create a List of integers
List<Integer> numberList = new ArrayList<>();
numberList.add(45);
numberList.add(12);
numberList.add(85);
numberList.add(32);
// Step 2: Print the original List
System.out.println("Original List: " + numberList);
// Step 3: Use the Collections.sort() method to sort the List
Collections.sort(numberList);
// Step 4: Print the sorted List
System.out.println("Sorted List: " + numberList);
}
}
Output:
Original List: [45, 12, 85, 32] Sorted List: [12, 32, 45, 85]
4. Step By Step Explanation
Step 1: A List of integers named numberList is created and initialized with some values.
Step 2: The original List is printed to the console.
Step 3: The Collections.sort() method is called to sort the elements of numberList in ascending order according to their natural ordering.
Step 4: The sorted List is printed to the console. As observed in the output, the elements of the List have been rearranged in ascending order.