how to do array sort java code example

Example 1: sort array java

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

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

// java sort arraylist
import java.util.ArrayList;
import java.util.Collections;
public class JavaSortArraylist 
{
   public static void main(String[] args) 
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Bear"); 
      al.add("Fox"); 
      al.add("Deer"); 
      al.add("Cheetah"); 
      al.add("Anteater");
      al.add("Elephant");
      System.out.println("Before sorting ArrayList: " + al);
      Collections.sort(al); 
      System.out.println("After sorting ArrayList in Ascending order: " + al);
   }
}

Example 4: Arrays.sort() in java

// java sort array of objects
import java.util.Arrays;
public class Employee implements Comparable<Employee>
{
   private String empName; 
   private int empAge;
   public Employee(String name, int age) 
   { 
      this.empName = name; 
      this.empAge = age; 
   }
   @Override 
   public String toString() 
   { 
      return "{" + "name='" + empName + '\'' + ", age=" + empAge + '}'; 
   }
   public String getName() 
   { 
      return empName; 
   }
   public int getAge() 
   { 
      return empAge; 
   }
   @Override 
   public int compareTo(Employee o) 
   { 
      if(this.empAge != o.getAge()) 
      { 
         return this.empAge - o.getAge(); 
      }
      return this.empName.compareTo(o.getName()); 
   }
}
public class SortArrayObjects 
{
   public static void main(String[] args) 
   {
      Employee[] obj = { new Employee("virat", 25), new Employee("dhoni", 20), 
                         new Employee("rohit", 22), new Employee("rahul", 24)};
      Arrays.sort(obj); 
      System.out.println(Arrays.toString(obj));
   }
}

Example 5: 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]));