Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to sort an Array of Strings in Java

  • Last Updated : 29 Nov, 2021

Array Of Strings

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

Java




// 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()
 

Java




// A sample Java program to sort
// an arrayList of strings
// in ascending and descending
// orders using Collections.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] 

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!