Different Ways of Array Sorting Techniques in Java with JUnit
Last Updated :
26 Apr, 2025
Accounting software /medical software / educational software etc. requires sorted data to be given for some analysis and also to prepare bar charts, pie charts, bar graphs, etc., In this tutorial let us see how to get sorted data in a java way. We need to know about the comparable interface and comparator interface also before moving further.
Comparable interface is in java.lang package and follows natural ordering and orders the data in ascending order/descending order format. It uses the compareTo method and according to the specification will get sorted either in ascending/descending order. No extra package is required.
For using the Comparator interface, we need to use java.util package and it uses compare method and compares the objects. In different ways, we can sort the data. For example, GeekEmployee with id, name, and age are available means, we can sort by means of name or by means of age, etc.,
As a sample maven project let us see the different ways carried out and also unit testing also covered in the project.
Example Maven Project
Project Structure:
pom.xml
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>java-arrays-sorting-techniques</artifactId>
<name>java-arrays-sorting-techniques</name>
<packaging>jar</packaging>
<parent>
<artifactId>java-arrays-sorting-techniques</artifactId>
<groupId>com.gfg</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Utilities -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- Benchmarking -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
</properties>
</project>
Let us first check out the java files
Model class
GeekEmployee.java
Java
import java.io.Serializable;
public class GeekEmployee implements Serializable {
private static final long serialVersionUID = -2454619097207585825L;
private int id;
private String name;
private int age;
public GeekEmployee() {
}
public GeekEmployee(int id, String name) {
this.id = id;
this.name = name;
}
public GeekEmployee(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public int getId() {
return id;
}
public void setAge(int age) {
this.age = age;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Let us do the sorting both in a comparator and comparable way
CheckingSortedArrayContents.java
Java
import java.util.Comparator;
public class CheckingSortedArrayContents {
boolean isSortedCheck1RecursiveWay(int[] array, int length) {
if (array == null || length < 2)
return true;
if (array[length - 2] > array[length - 1])
return false;
return isSortedCheck1RecursiveWay(array, length - 1);
}
boolean isSortedCheck2(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1])
return false;
}
return true;
}
boolean isSortedCheck3InComparableWay(Comparable[] array, int length) {
if (array == null || length < 2)
return true;
if (array[length - 2].compareTo(array[length - 1]) > 0)
return false;
return isSortedCheck3InComparableWay(array, length - 1);
}
boolean isSortedCheck4(Comparable[] array) {
for (int i = 0; i < array.length - 1; ++i) {
if (array[i].compareTo(array[i + 1]) > 0)
return false;
}
return true;
}
boolean isSortedCheck5InComparatorWay(Object[] array, Comparator comparator) {
for (int i = 0; i < array.length - 1; ++i) {
if (comparator.compare(array[i], (array[i + 1])) > 0)
return false;
}
return true;
}
boolean isSortedCheck6(Object[] array, Comparator comparator, int length) {
if (array == null || length < 2)
return true;
if (comparator.compare(array[length - 2], array[length - 1]) > 0)
return false;
return isSortedCheck6(array, comparator, length - 1);
}
}
It is always good to follow sorting in different ways
- sorting - WithForLoop
- sorting - WithCollectionsReverse
- sorting - WithCommonsLang
Let us see them via the below methods in a java file
DifferentWaysOfSorting.java
Java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
public class DifferentWaysOfSorting {
public void sortingWithForLoop(Object[] array) {
for (int i = 0; i < array.length / 2; i++) {
Object temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
public void sortingWithCollectionsReverse(Object[] array) {
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
}
public void sortingWithCommonsLang(Object[] array) {
ArrayUtils.reverse(array);
}
}
To confirm the above executions, always it is good to go with some unit tests
CheckingSortedArrayContentsUnitTest.java
Java
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
import com.gfg.model.GeekEmployee;
public class CheckingSortedArrayContentsUnitTest {
private static final int[] SORTEDINTEGERS = {10, 300, 5000, 70000, 900000};
private static final int[] NOTSORTEDINTEGERS = {100, 30, 11000, 7000};
private static final String[] SORTEDSTRINGS = {"champion", "geeks", "hackathon"};
private static final String[] NOTSORTEDSTRINGS = {"geeks", "champion", "tressurehunt", "hackathon"};
private static final GeekEmployee[] GEEKEMPLOYEESSORTEDBYNAME = {
new GeekEmployee(1, "Monica", 30),
new GeekEmployee(2, "Phoebe", 31),
new GeekEmployee(3, "Rachel", 27)};
private static final GeekEmployee[] GEEKEMPLOYEESNOTSORTEDBYNAME = {
new GeekEmployee(1, "Rachel", 31),
new GeekEmployee(2, "Monica", 26),
new GeekEmployee(3, "Phoebe", 27)};
private static final GeekEmployee[] GEEKEMPLOYEESSORTEDBYAGE = {
new GeekEmployee(1, "Ross", 28),
new GeekEmployee(2, "Chandler", 30),
new GeekEmployee(3, "Joey", 32)};
private static final GeekEmployee[] GEEKEMPLOYEESNOTSORTEDBYAGE = {
new GeekEmployee(1, "Chandler", 30),
new GeekEmployee(2, "Joey", 32),
new GeekEmployee(3, "Ross", 28)};
private CheckingSortedArrayContents sortedArrayChecker;
@Before
public void setup() {
sortedArrayChecker = new CheckingSortedArrayContents();
}
@Test
public void givenIntegerArray_thenReturnIfItIsSortedOrNot() {
assertThat(sortedArrayChecker.isSortedCheck2(SORTEDINTEGERS)).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedCheck2(NOTSORTEDINTEGERS)).isEqualTo(false);
assertThat(sortedArrayChecker.isSortedCheck1RecursiveWay(SORTEDINTEGERS, SORTEDINTEGERS.length)).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedCheck1RecursiveWay(NOTSORTEDINTEGERS, NOTSORTEDINTEGERS.length)).isEqualTo(false);
}
@Test
public void givenStringArray_thenReturnIfItIsSortedOrNot() {
assertThat(sortedArrayChecker.isSortedCheck4(SORTEDSTRINGS)).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedCheck4(NOTSORTEDSTRINGS)).isEqualTo(false);
assertThat(sortedArrayChecker.isSortedCheck3InComparableWay(SORTEDSTRINGS, SORTEDSTRINGS.length)).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedCheck3InComparableWay(NOTSORTEDSTRINGS, NOTSORTEDSTRINGS.length)).isEqualTo(false);
}
@Test
public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() {
assertThat(sortedArrayChecker.isSortedCheck5InComparatorWay(GEEKEMPLOYEESSORTEDBYNAME, Comparator.comparing(GeekEmployee::getName))).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedCheck5InComparatorWay(GEEKEMPLOYEESNOTSORTEDBYNAME, Comparator.comparing(GeekEmployee::getName))).isEqualTo(false);
assertThat(sortedArrayChecker.isSortedCheck5InComparatorWay(GEEKEMPLOYEESSORTEDBYAGE, Comparator.comparingInt(GeekEmployee::getAge))).isEqualTo(true);
assertThat(sortedArrayChecker.isSortedCheck5InComparatorWay(GEEKEMPLOYEESNOTSORTEDBYAGE, Comparator.comparingInt(GeekEmployee::getAge))).isEqualTo(false);
assertThat(sortedArrayChecker
.isSortedCheck6(GEEKEMPLOYEESSORTEDBYAGE, Comparator.comparingInt(GeekEmployee::getAge), GEEKEMPLOYEESSORTEDBYAGE.length))
.isEqualTo(true);
assertThat(sortedArrayChecker
.isSortedCheck6(GEEKEMPLOYEESNOTSORTEDBYAGE, Comparator.comparingInt(GeekEmployee::getAge), GEEKEMPLOYEESNOTSORTEDBYAGE.length))
.isEqualTo(false);
}
}
Output of JUnit:
DifferentWaysOfSortingUnitTest.java
Java
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class DifferentWaysOfSortingUnitTest {
private String[] employeeNames = { "rachel", "ross", "monica", "chandler", "joey", "phoebe" };
@Test
public void invertingArrayWithForLoopPattern() {
DifferentWaysOfSorting inverter = new DifferentWaysOfSorting();
inverter.sortingWithForLoop(employeeNames);
assertThat(new String[] { "phoebe", "joey", "chandler", "monica", "ross", "rachel" }).isEqualTo(employeeNames);
}
@Test
public void invertingArrayWithCollectionsReverse() {
DifferentWaysOfSorting inverter = new DifferentWaysOfSorting();
inverter.sortingWithCollectionsReverse(employeeNames);
assertThat(new String[] { "phoebe", "joey", "chandler", "monica", "ross", "rachel" }).isEqualTo(employeeNames);
}
@Test
public void invertingArrayWithCommonsLang() {
DifferentWaysOfSorting inverter = new DifferentWaysOfSorting();
inverter.sortingWithCommonsLang(employeeNames);
assertThat(new String[] { "phoebe", "joey", "chandler", "monica", "ross", "rachel" }).isEqualTo(employeeNames);
}
}
Output of JUnit:
Conclusion
According to our needs, arrays can be sorted out in java using comparable and comparator interface as the base. It is a good practice always to do unit testing for any piece of software. It helps to eradicate errors to the maximum extent and also it helps to determine the best pattern that suits requirements. It can be judged by means of the time required to complete the flow.
Similar Reads
Sort a String in Java (2 different ways)
The string class doesn't have any method that directly sorts a string, but we can sort a string by applying other methods one after another. The string is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. Creating a String T
6 min read
How to sort an Array of Strings in Java
Array Of StringsTo sort an array of strings in Java, we can use Arrays.sort() function. Java // A sample Java program to // sort an array of strings // in ascending and descending // orders using Arrays.sort(). import java.util.Arrays; import java.util.Collections; // Driver Class public class SortE
3 min read
Nested Map Assertions in Java with JUnit
In Java applications, nested data structures are commonplace, especially when dealing with configurations, JSON responses, or complex data representations. One such structure is the nested map. This article focuses on the theory behind nested maps, their structures, and the techniques used for asser
6 min read
ArrayList toArray() method in Java with Examples
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.Declaring toArray() methodpublic Object[] toArray() or public <T> T[] toArray(T[] a)Parameters: This method either accepts no parameters or it takes an array T[] as a para
3 min read
SortedMap comparator() method in Java with Examples
The comparator() method of java.util.SortedMap interface is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.Syntax: public Comparator comparator() Return Value: This method returns the comparator used to order the keys in th
2 min read
Difference Between TreeSet and SortedSet in Java
TreeSet is one of the implementations of the Navigable sub-interface. It is underlying data structure is a red-black tree. The elements are stored in ascending order and more methods are available in TreeSet compare to SortedSet. We can also change the sorting parameter using a Comparator. For examp
3 min read
ArrayList listIterator() Method in Java
The listIterator() method of ArrayList class in Java is used to return a ListIterator for traversing the elements of the list in proper sequence. The iterator allows both forward and backward traversal of the list.Example 1: Here, we use the listIterator() method to obtain a ListIterator over all el
3 min read
SortedSet toArray() method in Java with Examples
The toArray() method of Java SortedSet is used to form an array of the same elements as that of the SortedSet. Basically, it copies all the element from a SortedSet to a new array. Syntax: Object[] toArray() Parameters: The method does not take any parameters. Return Value: The method returns an arr
2 min read
JUnit 5 - Asserting Arrays and Lists with AssertJ
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development. JUnit 5 is the next generation of JUnit. AssertJ is a Java library that provides a rich set of assertions and truly helpful error messages, improves test code
6 min read
Collator compare(String, String) method in Java with Example
The compare() method of java.text.Collator class is used to compare the strength of two string and it will return 0, positive and negative values as an output according to the result. Syntax: public abstract int compare(String source, String target) Parameter: This method takes two strings between w
2 min read