JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

How to sort ArrayList ascending descending order

How to sort ArrayList ascending descending order 

Sorting ArrayList in Java is not difficult, by using Collections.sort() method you can sort ArrayList in ascending and descending order in Java. Collections.sort() method optionally accept a Comparator and if provided it uses Comparator's compare method to compare Objects stored in Collection to compare with each other, in case of no explicit Comparator, Comparable interface's compareTo() method is used to compare objects from each other. If object's stored in ArrayList doesn't implements Comparable than they can not be sorted using Collections.sort() method in Java.



Sorting ArrayList in Java – Code Example

ArrayList Sorting Example in Java - Ascending Descending Order Code

Here is a complete code example of How to sort ArrayList in Java, In this Sorting we have used Comparable method of String for sorting String on there natural order, You can also use Comparator in place of Comparable to sort String on any other order than natural ordering e.g. in reverse order by using Collections.reverseOrder() or in case insensitive order by using String.CASE_INSENSITIVE_COMPARATOR.





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

public class CollectionTest {

   
    public static void main(String args[]) {
   
        //Creating and populating ArrayList in Java for Sorting
        ArrayList<String> unsortedList = new ArrayList<String>();
       
        unsortedList.add("Java");
        unsortedList.add("C++");
        unsortedList.add("J2EE");
       
        System.err.println("unsorted ArrayList in Java : " + unsortedList);
       
        //Sorting ArrayList in ascending Order in Java
        Collections.sort(unsortedList);
        System.out.println("Sorted ArrayList in Java - Ascending order : " + unsortedList);
       
        //Sorting ArrayList in descending order in Java
        Collections.sort(unsortedList, Collections.reverseOrder());
        System.err.println("Sorted ArrayList in Java - Descending order : " + unsortedList);
    }
}
Output:
unsorted ArrayList in Java : [Java, C++, J2EE]
Sorted ArrayList in Java - Ascending order : [C++, J2EE, Java]
Sorted ArrayList in Java - Descending order : [Java, J2EE, C++]

.