Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Sort ArrayList in java - Testingpool

Sort ArrayList in java

In the previous post, we have seen how to remove an element at a specified index. In this post, we will see how to sort arraylist in java.

We use the collections class to sort the arraylist.

Syntax:

Collections.sort(arraylist)

Example for sorting String:

We will see how to sort the string.

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

public class ArrayListEx {

	public static void main(String[] args) {
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Orange");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Grapes");

		System.out.println("List of fruits before sorting : "+fruits);
		Collections.sort(fruits);  //sort the arraylist
		
		System.out.println("List of fruits after sorting : "+fruits);
	}
}

Output:

List of fruits before sorting : [Orange, Mango, Apple, Grapes] List of fruits after sorting : [Apple, Grapes, Mango, Orange]

 

Example for sorting the integer:

We will see how to sort the Integer values.

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

public class ArrayListEx {

	public static void main(String[] args) {
		ArrayList<Integer> num = new ArrayList<Integer>();
		num.add(4);
		num.add(2);
		num.add(6);
		num.add(1);

		System.out.println("List of integer before sorting : "+num);
		Collections.sort(num);  //sort the arraylist
		
		System.out.println("List of integer after sorting : "+num);
	}
}

Output:

List of integer before sorting : [4, 2, 6, 1] List of integer after sorting : [1, 2, 4, 6]

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum

 

 

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...