Java sort both primitive and object array

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn java sort both primitive and object array.

In the previous post we learnt how to sort an array in ascending and descending order. Meanwhile sort() method from java.util.Arrays class provide overloaded method to sort primitive data types namely double, long, float, byte, short, and char.

Now we will see different arrays of primitive type,

// sorting array of type byte 
byte byteArray[] = { 115, 102, 117, 12, 18 };
Arrays.sort(byteArray);

// sorting array of type char 
char charArray[] = { 'e', 'c', 'a', 'd', 'b' };
Arrays.sort(charArray);

// sorting array of type short 
short shortArray[] = { 415, 132, 600, 201, 229 };
Arrays.sort(shortArray);

// sorting array of type integer 
int intArray[] = { 4, 8, 6, 10, 2 };
Arrays.sort(intArray);

// sorting array of type long 
long[] longArray = { 15636, 526536, 653562, 231656, 325853 };
Arrays.sort(longArray);

// sorting array of type float 
float[] floatArray = { 11.5f, 21.52f, 61.45f, 29.5f, 810.14f };
Arrays.sort(floatArray);

// sorting array of type double 
double[] doubleArray = { 31.45d, 130.45d, 510.27d, 830.25d, 290.45d };
Arrays.sort(doubleArray);

Similarly, to sort object array in ascending order, compare() and compareTo() methods are used. Here compare() method sorts array in natural order while compareTo() method sorts array in custom order which implements comparable or comparator interface.

Also read – how to sort array in ascending order

Sort an array of Integer object

In this java program sort() method is used to sort Integer object. Also reverse ordered by passing reverseOrder comparator from Collections class.

import java.util.Arrays;
import java.util.Collections;

public class SortIntegerDemo 
{
public static void main(String[] args)
{
Integer number[] = {89, 59, 66, 91, 26, 33};
Arrays.sort(number);
System.out.println("ascending : " + Arrays.toString(number));
Arrays.sort(number, Collections.reverseOrder());
System.out.println("reverse : " + Arrays.toString(number));
}
}

Output:

ascending : [26, 33, 59, 66, 89, 91]
reverse : [91, 89, 66, 59, 33, 26]

Sort string array – ascending and descending order

String sorts in alphabetical order. So while sorting String array, it sorts in natural way defined in Comparable interface.

import java.util.Arrays;
import java.util.Collections;

public class SortStringDemo 
{
public static void main(String[] args)
{
String players[] = {"Zaheer", "Sachin", "Rahul", "Ajinkya", "Dhoni"};
System.out.println("Before sorting : " + Arrays.toString(players));
Arrays.sort(players);
System.out.println("ascending order : " + Arrays.toString(players));
Arrays.sort(players, 0, players.length, Collections.reverseOrder());
System.out.println("descending order : " + Arrays.toString(players));
}
}

Output:

Before sorting : [Zaheer, Sachin, Rahul, Ajinkya, Dhoni]
ascending order : [Ajinkya, Dhoni, Rahul, Sachin, Zaheer]
descending order : [Zaheer, Sachin, Rahul, Dhoni, Ajinkya]

Sort object array using Comparator and Comparable interface

To sort an object array, each and every element in an array should implement Comparator or Comparable interface.

Also read – sort string array in java

sort(Object[ ]) method is used to sort object in natural order and sort(T[ ], Comparator) method in custom order.

import java.util.Comparator;

public class Employee implements Comparable<Employee>
{
int empID;
String empName;
int empSalary;
   public Employee(int empID, String empName, int empSalary)
{
this.empID = empID;
this.empName = empName;
this.empSalary = empSalary;
}

@Override
public int compareTo(Employee a)
{
return this.empID - a.empID;
}

@Override
public String toString()
{
return String.format("#%d %s@%d ", empID, empName, empSalary);
}

public static class SalaryComparator implements Comparator<Employee>
{
@Override
public int compare(Employee c1, Employee c2)
{
return c1.empSalary - c2.empSalary;
}
}

public static class NameComparator implements Comparator<Employee>
{
@Override
public int compare(Employee c1, Employee c2)
{
return c1.empName.compareTo(c2.empName);
}
}
}


import java.util.Arrays;

public class SortObjectDemo
{
public static void main(String[] args)
{
Employee[] emp = new Employee[4];
emp[0] = new Employee(5001, "Jay", 7000);
emp[1] = new Employee(6001, "Rohan", 5000);
emp[2] = new Employee(7001, "Piyush", 3000);
emp[3] = new Employee(8001, "Sachin", 4000);

  System.out.println("Before sorting : " + Arrays.toString(emp));

  Arrays.sort(emp);
  System.out.println("After sorting, natural order : " + Arrays.toString(emp));

  Arrays.sort(emp, new Employee.SalaryComparator());
  System.out.println("After sorting by salary : " + Arrays.toString(emp));

  Arrays.sort(emp, new Employee.NameComparator());
  System.out.println("After sorting by name : " + Arrays.toString(emp));
  }
}

Output:

Before sorting : [#5001 Jay@7000 , #6001 Rohan@5000 , #7001 Piyush@3000 , #8001 Sachin@4000 ]
After sorting, natural order : [#5001 Jay@7000 , #6001 Rohan@5000 , #7001 Piyush@3000 , #8001 Sachin@4000 ]
After sorting by salary : [#7001 Piyush@3000 , #8001 Sachin@4000 , #6001 Rohan@5000 , #5001 Jay@7000 ]
After sorting by name : [#5001 Jay@7000 , #7001 Piyush@3000 , #6001 Rohan@5000 , #8001 Sachin@4000 ]

Sorting an array in java in descending order using Arrays.sort()

Now let’s learn java sort array in descending order using Arrays.sort(). By default Arrays.sort() method sorts array in ascending order.

Also read – java sort string array alphabetically

To sort array in descending order in java we reverse the result after sorting using reverse() method.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortArrayDescending 
{
public static void main(String[] args)
{
Integer arrDesc[] = { 4, 1, 6, 2, 8 };
Arrays.sort(arrDesc);
List<Integer> li = Arrays.asList(arrDesc);
Collections.reverse(li);
li.toArray(arrDesc);
System.out.println("Descending order : " + Arrays.toString(arrDesc));
}
}

Output:

Descending order : [8, 6, 4, 2, 1]


Using custom comparator we can sort array in descending order.

import java.util.Arrays;
import java.util.Comparator;

public class SortDescending 
{
public static void main(String[] args)
{
Integer arrDesc[] = { 4, 1, 6, 2, 8 };
Arrays.sort(arrDesc, new Comparator<Integer>()
{
@Override
public int compare(Integer arg0, Integer arg1)
{
return -1 * arg0.compareTo(arg1);    // logic is reversed here by multiplying the result of compareTo with -1
}});
System.out.println("Descending order : " + Arrays.toString(arrDesc));
}
}

Output :

Descending order : [8, 6, 4, 2, 1]

So, we have understood that sorting object array is very simple. Since java provides sort() method which accepts array and Comparator to sort array in reverse order.

Sort two dimensional array

There is no method in java to sort two, three or multi dimensional array. Using ColumnComparator class we can sort columns. This class implements Comparator interface to sort column data.

Also java enum is used to define sorting, that is, ascending or descending.

import java.util.Arrays;
import java.util.Comparator;

public class SortTwoDimensionalDemo 
{
public static void main(String[] args)
{
Integer num[][] = {{6, 7, 2}, {1, 5, 3}, {4, 8, 9}};
System.out.println("Before sort : " + Arrays.deepToString(num));
Arrays.sort(num, new ColumnComparator(0, SortingOrder.ASCENDING));
System.out.println("First column ascending order : " + Arrays.deepToString(num));
Arrays.sort(num, new ColumnComparator(1, SortingOrder.DESCENDING));
System.out.println("Second column, ascending order : " + Arrays.deepToString(num));
}
}
enum SortingOrder
{
ASCENDING, DESCENDING;
};
class ColumnComparator implements Comparator<Comparable[]>
{
private final int col;
private final SortingOrder sort;
   public ColumnComparator(int column, SortingOrder order)
{
this.col = column;
this.sort = order;
}

@Override
public int compare(Comparable[] c1, Comparable[] c2)
{
int output = c1[col].compareTo(c2[col]);
return sort == SortingOrder.ASCENDING ? output : - output;
}
}

Output:

Before sort : [[6, 7, 2], [1, 5, 3], [4, 8, 9]]
First column ascending order : [[1, 5, 3], [4, 8, 9], [6, 7, 2]]
Second column, ascending order : [[4, 8, 9], [6, 7, 2], [1, 5, 3]]

Related Posts