What is ArraySorter.sort in Java?
sort() is a ArraySorter class that is used to sort an array of elements. It optionally takes a comparator to customize the order of the elements. By default, the method sorts the array in ascending order. The method sorts the array in place.
Refer to What is the Java Comparator interface? to learn more about the comparator.
How to import ArraySorter
The definition of ArraySorter can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the ArraySorter class as follows.
import org.apache.commons.lang3.ArraySorter;
Syntax
public static <T> T[] sort(final T[] array, final Comparator<? super T> comparator)
Parameters
final T[] array: The array of elements to sort.final Comparator<? super T> comparator: The comparator to determine the ordering of the elements.
Return value
This method returns the given array after being sorted.
Code
import org.apache.commons.lang3.ArraySorter;import java.util.Arrays;import java.util.Comparator;public class Main{static class Temp implements Comparator<Temp>{int a;public Temp(int a) {this.a = a;}@Overridepublic String toString() {return "Temp{" +"a=" + a +'}';}@Overridepublic int compare(Temp o1, Temp o2) {return 0;}}public static void main(String[] args){int[] ints = {2,4,1,5,2,3,2,-1,-34};System.out.printf("The output of ArraySorter.sort() for the array - '%s'", Arrays.toString(ints));ArraySorter.sort(ints);System.out.printf(" is '%s'", Arrays.toString(ints));System.out.println();Temp[] temps = {new Temp(9), new Temp(10), new Temp(5), new Temp(3)};System.out.printf("The output of ArraySorter.sort() for the array - '%s'", Arrays.toString(temps));ArraySorter.sort(temps, (o1, o2) -> o1.a - o2.a);System.out.printf(" is '%s'", Arrays.toString(temps));System.out.println();}}
Output
The output of ArraySorter.sort() for the array - '[2, 4, 1, 5, 2, 3, 2, -1, -34]' is '[-34, -1, 1, 2, 2, 2, 3, 4, 5]'
The output of ArraySorter.sort() for the array - '[Temp{a=9}, Temp{a=10}, Temp{a=5}, Temp{a=3}]' is '[Temp{a=3}, Temp{a=5}, Temp{a=9}, Temp{a=10}]'
Explanation
Example 1
- array =
[2, 4, 1, 5, 2, 3, 2, -1, -34]
The method returns the sorted array: [-34, -1, 1, 2, 2, 2, 3, 4, 5]
Example 2
- array:
[new Temp(9), new Temp(10), new Temp(5), new Temp(3)]
In the second example, in line 36 we define a custom class, Temp, and an array of instances of the Temp class. In order to sort the array of instances, we pass a custom comparator that returns the difference between the values of the attribute a for two instances of the class Temp.
The method returns the sorted array: [Temp{a=9}, Temp{a=10}, Temp{a=5}, Temp{a=3}]' is '[Temp{a=3}, Temp{a=5}, Temp{a=9}, Temp{a=10}]