Site icon

Sort Objects in ArrayList collection in ascending & descending order

1. Sort Objects of ArrayList in ascending & descending order:

  1. Given an ArrayList collection of string objects in java.
  2. We would like to:
    1. Sort elements of collection in ascending order.
    2. Sort elements of collection in descending order.

2.  Sort String objects of arraylist in ascending & descending order.

package org.learn.collection.list.arrayList;

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

public class SortElementInArrayList {

	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<>();
		arrayList.add("archery");
		arrayList.add("badminton");
		arrayList.add("canoe");
		arrayList.add("boxing");
		arrayList.add("diving");
		arrayList.add("beach volleyball");

		System.out.println("Sort elements or String objects of arrayList: ");
		demoSortMethod(arrayList);		
	}	

	private static void demoSortMethod(ArrayList<String> arrayList) {
		// [archery, badminton, canoe, boxing, diving, beach volleyball]
		System.out.println("Orignal ArrayList:" + arrayList);
		Collections.sort(arrayList);
		System.out.println("1. Sort arraylist in ascending order: " + arrayList);

		Collections.sort(arrayList, Collections.reverseOrder());
		System.out.println("2. Sort arraylist in descending order: " + arrayList);
	}	
}

3. Sort elements of arraylist in ascending & descending order

Sort elements or String objects of arrayList: 
Orignal ArrayList:[archery, badminton, canoe, boxing, diving, beach volleyball]
1. Sort arraylist in ascending order: [archery, badminton, beach volleyball, boxing, canoe, diving]
2. Sort arraylist in descending order: [diving, canoe, boxing, beach volleyball, badminton, archery]
Exit mobile version