Sort ArrayList Elements in Ascending Order in Java

Published by user on

In this article, we will see how to sort ArrayList elements in ascending order using a Collections.sort(List list) method.

Examples :
Input: 23, 54, 32, 56, 78, 65
Output: 23, 32, 54, 56, 65, 78

Input: Microsoft, Vmware, Salesforce, Apple, Facebook
Output: Apple, Facebook, Microsoft, Salesforce, Vmware

Example 1:

The below programs shows how to use sort(List list) to sort ArrayList elements in ascending order. Here the elements are of Integer type.

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListSortExample {

	public static void main(String[] args) {
		ArrayList<Integer> numbers = new ArrayList<>();
		numbers.add(23);
		numbers.add(54);
		numbers.add(32);
		numbers.add(56);
		numbers.add(78);
		numbers.add(65);

		System.out.println("ArrayList elements before sorting : " + numbers);
		Collections.sort(numbers);
		System.out.println("ArrayList elements after sorting in ascending order : " + numbers);
	}
}

Output:

ArrayList elements before sorting : [23, 54, 32, 56, 78, 65]
ArrayList elements after sorting in ascending order : [23, 32, 54, 56, 65, 78]

Example 2:

Let’s look at the program.

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListDemo {

	public static void main(String[] args) {
		ArrayList<String> companies = new ArrayList<>();
		companies.add("Microsoft");
		companies.add("Vmware");
		companies.add("Salesforce");
		companies.add("Apple");
		companies.add("Facebook");

		System.out.println("ArrayList elements before sorting: " + companies);
		Collections.sort(companies);
		System.out.println("ArrayList elements after sorting in ascending order: " + companies);
	}
}

Output:

ArrayList elements before sorting: [Microsoft, Vmware, Salesforce, Apple, Facebook] 
ArrayList elements after sorting in ascending order: [Apple, Facebook, Microsoft, Salesforce, Vmware]

That’s all for this article. Please share this if you like it.

Further Reading:

ArrayList Documentation.

Categories: Java