Newsletter

How To Sort An ArrayList In Java

Core Java » on Feb 17, 2014 { 4 Comments } By Sivateja

This is one of the famous interview questions for freshers and even for the experienced developers 🙂 let us see how to sort the ArrayList in java. We have a class Collections in java.util package, which will do this magic for us. Consider an example…

package java4s;

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

public class SortingArrayList {

    public static void main(String args[]){

       ArrayList<String> al = new ArrayList<String> ();

            al.add("22");
            al.add("33");
            al.add("11");
            al.add("cc");
            al.add("bb");
            al.add("aa");

            System.out.println("Printing List before sorting......");
             for(String value: al){
                 System.out.println(value);
             }

             //Sorting...
             Collections.sort(al);

             System.out.println("Printing List after sorting......");
             for(String value: al){
                System.out.println(value);
             }
}
}

Output

Printing List before sorting……
22
33
11
cc
bb
aa
Printing List after sorting……
11
22
33
aa
bb
cc

​ ​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

4 Responses to “How To Sort An ArrayList In Java”
  1. mani says:

    the above program doest produce expected output…
    there is a problem in sorting…
    any one tell me the reason…???

  2. CAN U PLEASE WRITE THE ABOVE PROGRAM WITHOUT USING COLLECTIONS.SORT()METHOD

  3. Tarique Anwer says:

    How Collections.sort(al) methods invokes the compare() of Comparator or compareTo() of Comparable interface in case of custom sorting.
    It will be great if you could explain only internal working for the same. I know the implementations.

  4. MOHAMMAD SALEEM BASHA says:

    I need a java code for following question

    1. how to find missing elements in an array,if i give input like 1,2,3,4,7,8. the output will be generated as the missing elements are 5,6.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.