Sorting a List: Sort an ArrayList of integers

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:

  1. Import Statements: We import the necessary classes, including ArrayList, List, and Collections from the java.util package.
  2. Creating the List: We create an ArrayList named numbers and populate it with some integers.
  3. Printing the Original List: We print the contents of the numbers list using System.out.println().
  4. 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.
  5. Printing the Sorted List: We print the contents of the sorted numbers list using System.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.

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *