Java - Sort array

By xngo on June 14, 2019

java.util.Arrays library provides a sort method to sort arrays of different type of objects. Therefore, there is no need to reinvent the wheel. Let's see how this method works with the code below.

Sort in ascending order

The code below will sort the list of fruits in ascending order.

import java.util.Arrays;
 
public class SortArrayAsc {
 
    public static void main(String[] args) {
 
        String[] fruits = new String[]{"banana", "avocado", "guava"};
 
        Arrays.sort(fruits); // Sort in ascending order.
 
        for(int i=0; i<fruits.length; i++ ) {
            System.out.println(fruits[i]);
        }
    }
}

Output

avocado
banana
guava

Sort in descending order

To sort in descending order, you need to provide a comparator to Arrays.sort() that sorts the elements in reverse. Luckily, Collections.reverseOrder() function returns a reverse order comparator. So, let's use it.

import java.util.Arrays;
import java.util.Collections;
 
public class SortArrayDesc {
 
    public static void main(String[] args) {
 
        String[] fruits = new String[]{"banana", "avocado", "guava"};
 
        Arrays.sort(fruits, Collections.reverseOrder()); // Sort in descending order.
 
        for(int i=0; i<fruits.length; i++ ) {
            System.out.println(fruits[i]);
        }
    }
}

Output

guava
banana
avocado

Sort in user-defined order

To sort using your own order, you have to implement your own comparator class. Here is an example of a comparator that sort on the second character of a string in descending order.

import java.util.Arrays;
import java.util.Comparator;
 
public class SortArrayUsingComparator {
    // Implement my own comparator class with my own order logic.
    public static class SortOn2ndChar implements Comparator<String>
    {
        // compare() should return -1, 0, 1 depending on your own logic.
        public int compare(String s1, String s2) {
 
            char s1char = s1.charAt(1); // Get 2nd character of 1st string.
            char s2char = s2.charAt(1); // Get 2nd character of 2nd string.
            if (s1char > s2char)
                return -1;
            else if(s1char < s2char)
                return 1;
            else
                return 0;
        }
    }
 
    public static void main(String[] args) {
 
        String[] fruits = new String[]{"banana", "avocado", "guava"};
 
        Arrays.sort(fruits, new SortOn2ndChar());
 
        for(int i=0; i<fruits.length; i++ ) {
            System.out.println(fruits[i]);
        }
    }
}

Output

avocado // 2nd char = v
guava   // 2nd char = u
banana  // 2nd char = a

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.