{

Best 10 Java Array Sort examples with strings numbers and objects


Best Array Sort Examples in java

You can also check my previous post on array tutorials with examples

Arrays Sort Examples

Array is a collection of elements stored under a single name.

Sort is based on ascending or descending order. For numbers,Ascending order means lowest number to highest number i.e Number will be increasing order. descending order means highest number to lowest number ie numbers will be decreasing order.

For Alphabets, A, B, C is a natural order and ascending order, and C, B, A is the reverse of ascending and descending order.

This post is about various Best Arrays sort examples in java.

Arrays.sort method java examples

java.util.Arrays. sort method is used to sort the primitive types as well as objects.

public static void sort(T[] a, Comparator c)

parameters are:-

The first parameter is any object or primitive.

The second is Comparator- this is a function for comparing the values in an array. It allows the order of the array to return.

Sort Array of Numbers in ascending order?

Array in java can store with integer, long types java This example sorts an integers array in ascending order

The arrays method contains a sort method that sorts and mutates the array in a natural(ascending) sorting order.

import java.util.Arrays;

public class ArraySortTest {
    public static void main(String[] args) {
        Integer[] numbers = { 5,3,17,1};
        System.out.println(Arrays.toString(numbers));
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));
    }
}

Output is

Original:[5, 3, 17, 1]  
Sorted asc order:[1, 3, 5, 17]  

How to sort integer arrays in descending order?

The sort() method without comparator returns the elements in ascending order. To sort descending order, Either you need to write your comparator or use the Collections.reverseOrder() method.

Here Comparator is supplied as Collections.reverse()order

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

public class ArraySortTest {
    public static void main(String[] args) {
        Integer[] numbers = { 5,3,17,1};
        System.out.println("Original:"+Arrays.toString(numbers));
        Arrays.sort(numbers, Collections.reverseOrder());
        System.out.println("Sorted desc order:"+Arrays.toString(numbers));
    }
}

Output:

Original:[5, 3, 17, 1]  
Sorted desc order:[17, 5, 3, 1]  

How to sort String arrays in ascending order?

pass string array to sort method, this returns the string array in ascending(natural ) order.

The result array displays elements in alphabetical order.

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

public class ArraySortTest {
    public static void main(String[] args) {
        String[] strs = { "one", "two", "three", "four", "five" ,"five"};
        System.out.println("Original:"+Arrays.toString(strs));
        Arrays.sort(strs);
        System.out.println("Sorted asc order:"+Arrays.toString(strs));

    }
}

Output

Original:[one, two, three, four, five, five]  
Sorted asc order:[five, five, four, one, three, two]  

How to sort String arrays in descending order?

pass reverseOrder() comparator to Array.sort() method to order in descending order.

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

public class ArraySortTest {
    public static void main(String[] args) {
        String[] strs = { "one", "two", "three", "four", "five" ,"five"};
        System.out.println("Original:"+Arrays.toString(strs));
        Arrays.sort(strs,Collections.reverseOrder());
        System.out.println("Sorted desc order:"+Arrays.toString(strs));

    }
}

Output is

Original:[one, two, three, four, five, five]  
Sorted desc order:[two, three, one, four, five, five]  

How to sort a Two-dimensional array in java?

Two-dimensional Arrays are arrays containing arrays. You have to write a comparator to sort elements in a two-dimensional array
It works on all versions of java.

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

public class ArraySortTest {
    public static void main(String[] args) {
        int[][] arrays = { { 3, 9 }, { 2, 5 }, {18, 19 }, { 41, 3 }, { 15, 4 } };
        System.out.println("Original:"+Arrays.deepToString(arrays));
        Arrays.sort(arrays, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return ((Integer) o2[0]).compareTo(o1[0]);
            }
        });
        System.out.println("Sorted:"+Arrays.deepToString(arrays));
    }
}

The same code was rewritten using java 8 streams

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

public class ArraySortTest {
    public static void main(String[] args) {
        int[][] arrays = { { 3, 9 }, { 2, 5 }, {18, 19 }, { 41, 3 }, { 15, 4 } };
        System.out.println("Original:"+Arrays.deepToString(arrays));
        Arrays.sort(arrays, Comparator.comparing((int[] arr) -> arr[0])
                .reversed());

        System.out.println("Sorted:"+Arrays.deepToString(arrays));
    }
}

output is

[[3, 9], [2, 5], [18, 19], [41, 3], [15, 4]]  
[[41, 3], [18, 19], [15, 4], [3, 9], [2, 5]]  

How to sort and merge integer arrays in java?

  • Created two arrays with inline initialization
  • sum two arrays' lengths and create a new array with this sum
  • Copy both array objects to a new array using arrayCopy
  • Finally, Method does sort a new array using the Arrays. sort() method
import java.util.Arrays;

public class ArraySortTest {
    public static void main(String[] args) {
        Integer array1[] = { 9, 5, 71 };
        Integer array2[] = { 21, 50, 1 };
        Integer output[] = new Integer[array1.length + array2.length];
        System.arraycopy(array1, 0, output, 0, array1.length);
        System.arraycopy(array2, 0, output, array1.length, array2.length);
        Arrays.sort(output);
        System.out.println(Arrays.toString(output));
    }
}
[1, 5, 9, 21, 50, 71]  

How to sort Custom Object Arrays in ascending or descending order?

Create an Employee object with id and salary fields.

 class Employee implements Comparable<Employee> {
    Integer id;
    Integer salary;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getSalary() {
        return salary;
    }
    public void setSalary(Integer salary) {
        this.salary = salary;
    }
    Employee(Integer id, Integer salary) {
        this.id = id;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", salary=" + salary + "]";
    }
    @Override
    public int compareTo(Employee o) {
         return this.salary - o.salary;
     }
 }

Sort Employees based on salary ascending order:

import java.util.Arrays;
public class ArraySortTest {
    public static void main(String[] args) {
        Employee[] emps = new Employee[3];
        emps[0] = new Employee(1, 4000);
        emps[1] = new Employee(2, 60000);
        emps[2] = new Employee(3, 5000);
        Arrays.sort(emps);
        for (int i = 0; i < emps.length; i++) {
            Employee emp = emps[i];
            System.out.println(emp);
        }
    }
}
Employee [id=1, salary=4000]  
Employee [id=3, salary=5000]  
Employee [id=2, salary=60000]  

Sort Employees based on salary descending order:

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

public class ArraySortTest {
    public static void main(String[] args) {
        Employee[] emps = new Employee[3];
        emps[0] = new Employee(1, 4000);
        emps[1] = new Employee(2, 60000);
        emps[2] = new Employee(3, 5000);
        Arrays.sort(emps, Collections.reverseOrder());
        for (int i = 0; i < emps.length; i++) {
            Employee emp = emps[i];
            System.out.println(emp);
        }
    }
}

Output is

Employee [id=2, salary=60000]  
Employee [id=3, salary=5000]  
Employee [id=1, salary=4000]  

Conclusion

You learned some basic examples of Array sorting in ascending and descending order in java.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.