Problem Statement: Implement a Java program to sort an ArrayList of integer numbers.
Here’s a Java program that demonstrates how to sort an ArrayList
of integers using the built-in Collections.sort()
method. I’ll provide you with an explanation of the program’s logic.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortArrayListDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
numbers.add(3);
System.out.println("Original List: " + numbers);
// Sorting the ArrayList
Collections.sort(numbers);
System.out.println("Sorted List: " + numbers);
}
}
OUTPUT:
Original List: [5, 2, 8, 1, 3]
Sorted List: [1, 2, 3, 5, 8]
Explanation:
- Import Statements: We import the necessary classes, including
ArrayList
,List
, andCollections
from thejava.util
package. - Creating the List: We create an
ArrayList
namednumbers
and populate it with some integers. - Printing the Original List: We print the contents of the
numbers
list usingSystem.out.println()
. - Sorting the List: We use the
Collections.sort()
method to sort the numbers list in ascending order. This method sorts the list in place, meaning it modifies the original list rather than creating a new sorted list. - Printing the Sorted List: We print the contents of the sorted
numbers
list usingSystem.out.println()
.
By calling Collections.sort(numbers)
, we sort the ArrayList
of integers in ascending order. The result is a list of integers that have been rearranged from their original order. The Collections.sort()
method works for any List
of objects that implement the Comparable
interface, which includes the built-in types like Integer
.
See also: Find duplicate elements in an ArrayList.