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