Open In App

Different Ways of Array Sorting Techniques in Java with JUnit

Improve
Improve
Like Article
Like
Save
Share
Report

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:

Project Structure

 

pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
    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.



Last Updated : 21 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads