Skip to content
Related Articles

Related Articles

Improve Article

How to sort an Array of Strings in Java

  • Last Updated : 22 Jul, 2021

Array Of Strings

To sort an array of strings in Java, we can use Arrays.sort() function.




// A sample Java program to
// sort an array of strings
// in ascending and descending
// orders using Arrays.sort().
  
import java.util.Arrays;
import java.util.Collections;
  
public class SortExample {
    public static void main(String[] args)
    {
        String arr[] = { "practice.geeksforgeeks.org",
                         "quiz.geeksforgeeks.org",
                         "code.geeksforgeeks.org" };
  
        // Sorts arr[] in ascending order
        Arrays.sort(arr);
        System.out.printf("Modified arr[] : \n%s\n\n",
                          Arrays.toString(arr));
  
        // Sorts arr[] in descending order
        Arrays.sort(arr, Collections.reverseOrder());
  
        System.out.printf("Modified arr[] : \n%s\n\n",
                          Arrays.toString(arr));
    }
}
Output:

Modified arr[] :

Modified arr[] :
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]



ArrayList Of Strings

If we have an ArrayList to sort, we can use Collections.sort()




// A sample Java program to sort
// an arrayList of strings
// in ascending and descending
// orders using Coolections.sort().
  
import java.util.ArrayList;
import java.util.Collections;
  
public class SortExample {
    public static void main(String[] args)
    {
        ArrayList<String> al = new ArrayList<String>();
        al.add("practice.geeksforgeeks.org");
        al.add("quiz.geeksforgeeks.org");
        al.add("code.geeksforgeeks.org");
  
        // Sorts ArrayList in ascending order
        Collections.sort(al);
        System.out.println(
            "Modified ArrayList : \n" + al);
  
        // Sorts arr[] in descending order
        Collections.sort(al,
                         Collections.reverseOrder());
  
        System.out.println(
            "Modified ArrayList : \n" + al);
    }
}
Output:

Modified ArrayList :

Modified ArrayList :
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :