In this tutorial you will learn how to sort ArrayList of String or Integer in Java.
We can easily sort an arraylist in ascending or descending order using Collections.sort() method.
Below I have shared simple example for each of them.
Sort ArratList in Java
Example to Sort ArrayList of String
Below program sorts an arraylist of String type.
package com; import java.util.ArrayList; import java.util.Collections; public class SortStringArrayList { public static void main(String args[]){ ArrayList<String> aList = new ArrayList<String>(); aList.add("Android"); aList.add("Windows"); aList.add("IOS"); aList.add("Linux"); aList.add("Mac"); System.out.println("Sort in ascending order"); Collections.sort(aList); for(String s:aList){ System.out.println(s); } System.out.println("\nSort in descending order"); Collections.sort(aList,Collections.reverseOrder()); for(String s:aList){ System.out.println(s); } } }
Output
Sort in ascending order
Android
IOS
Linux
Mac
Windows
Sort in descending order
Windows
Mac
Linux
IOS
Android
Example to Sort ArrayList of Integer
Below program sorts an arraylist of Integer type.
package com; import java.util.ArrayList; import java.util.Collections; public class SortIntegerArrayList { public static void main(String args[]){ ArrayList<Integer> aList = new ArrayList<Integer>(); aList.add(20); aList.add(15); aList.add(25); aList.add(10); aList.add(30); System.out.println("Sort in ascending order"); Collections.sort(aList); for(Integer i:aList){ System.out.println(i); } System.out.println("\nSort in descending order"); Collections.sort(aList,Collections.reverseOrder()); for(Integer i:aList){ System.out.println(i); } } }
Output
Sort in ascending order
10
15
20
25
30
Sort in descending order
30
25
20
15
10
You can ask your queries by commenting below.
What if i create an arraylist itβs type Human , it contains names and ages
And i want to sort names alone then sort ages ?
Yes, you can do this using Comparable and Comparator. Just read below tutorial.
https://thejavaprogrammer.com/sort-arraylist-objects-java/
Thanks for visiting this blog π
Now you must have understood the importance of these interfaces. Let s see how to use them to get the sorting done in our way.