java sorting array code example

Example 1: sort array java

import java. util. Arrays;
Arrays. sort(array);

Example 2: Arrays.sort() in java

// java program to sort strings in an alphabetical order
import java.util.Arrays;
public class SortStringAlphabeticalOrder
{
   public static void main(String[] args)
   {
      String[] strAsc = {"Bear","Fox","Deer","Cheetah","Anteater","Elephant"};
      System.out.println("Before sorting: ");
      for(String string : strAsc)
      {
         System.out.println(string);
      }
      // arrays.sort
      Arrays.sort(strAsc);
      System.out.println("-----------------------------------");
      System.out.println("After sorting: ");
      for(String str : strAsc)
      {
         System.out.println(str);
      }
   }
}

Example 3: 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 4: Arrays.sort() in java

// how to sort an array of strings in descending
import java.util.Arrays;
import java.util.Collections;
public class SortStringAlphabeticalOrder 
{
   public static void main(String[] args) 
   {
      String[] strDesc = {"Bear","Fox","Deer","Cheetah","Anteater","Elephant"};
      System.out.println("Before sorting: ");
      for(String string : strDesc)
      {
         System.out.println(string);
      }
      // arrays.sort
      Arrays.sort(strDesc, Collections.reverseOrder());   
      System.out.println("-----------------------------------");
      System.out.println("Sorting string array in descending or reverse order: ");
      for(String string : strDesc)
      {
         System.out.println(string);
      }
   }
}

Example 5: java sort method

Arrays.sort();//this method is an inbuild function in java
//to sort the array

Example 6: java array sort by element

//sort array of array of integer by the second element;
int[][] array = new int[m][2];
//initialize array
Arrays.sort(array, (a,b)-> Integer.compare(a[1], b[1]));