sorting array in ascending order java array code example

Example 1: efficient way to sort an array in java

enum Code {
    Str1(1), Str2(2), Str3(3), Str4(4), Str5(5));

    int sortNumber;

    Code(int sortNumber) {
        this.sortNumber = sortNumber;
    }

    int returnNumber() {
        return sortNumber;
    }
};

public static void main(String[] args) {
    List<Object> obj = new ArrayList<Object>();

    Collections.sort(obj, new Comparator<Object>() {
        @Override
        public int compare(Object object1, Object object2) {
            return Code.valueOf(object1.getStr()).returnNumber() > Code.valueOf(object2.getStr()).returnNumber() ? 1 : -1;
        }
    });
}

Example 2: sorting array in ascending order java

import java.util.Arrays;
public class JavaArraySortMethod
{
   public static void main(String[] args)
   {
   String[] strGiven = {"Great Barrier Reef", "Paris", "borabora","tokyo", "Cusco"};
   Arrays.sort(strGiven);
   System.out.println("Output(case sensitive) : " + Arrays.toString(strGiven));
   }
}

Tags:

Java Example