Verification: 52bc5e43554438b2
Java

how to Sort an Array and list in ascending and descending order in java

Description:

How to Sort an Array and list in ascending and descending order in java-In this article, you will learn how to sort an array in ascending or descending order using different techniques, and I will also explain how to use it in other applications. This time, I will explain sorting in an easy-to-understand manner. So In this article, we will cover the following topics.

  • When sorting List with Comparator
  • How to use strings array sorting
  • sorting an array by multiple keys



Fixed Length Array Sorting

To sort an array (fixed length), use the sort method of the Array class. Describe it as follows.

Arrays.sort (array name);

This line of code is used to sort an array in ascending order. What if you want to sort in descending order? Specify the reverseOrder method of the Collections class as the second argument of the sort method. The description is as follows.

Arrays.sort (array name, Collections.reverseOrder()); 

The reverseOrder method returns a comparator that reverses the order. A comparator is an interface for a class that performs comparison processing. Comparators will be explained in detail later.

When using the Collections class, the sorted array must be of class type, such as Integer. Note that an error will occur if you specify a primitive type such as int.


How to sort an array in ascending order:

Let’s check the sample code for sorting an array in ascending order.

package com.mycompany.javabasics;

import java.util.Arrays;

/**
 *
 * @author Fawadkhan
 */
public class JavaArrayExample {

    public static void main(String[] args) {

        int[] data1 = {6, 2, 4, 1, 3, 5};

        Arrays.sort(data1);

        for (int i : data1) {
            System.out.println(i);
        }

    }

}

output:

Sort

How to sort an array in descending order:

Now let’s check the sample code for sorting an array in descending order.

package com.mycompany.javabasics;

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

/**
 *
 * @author Fawadkhan
 */
public class JavaArrayExample {

    public static void main(String[] args) {

        Integer[] data1 = {6, 2, 4, 1, 3, 5};

        Arrays.sort(data1, Collections.reverseOrder());

        System.out.println(Arrays.asList(data1));

    }

}

output:

Sort

Since this sample code uses the Collections class, the array is declared as the Integer type, not the int type.

To sort in descending order, the second argument of the sort method of the Arrays class specifies the reverseOrder method of the Collections class.


Sorting a List:

To sort the elements of a List type object, use the sort method of the Collections class . Describe it as follows.

Collections.sort (list name);

In the above description, you can sort in ascending order. To sort in descending order, specify the reverseOrder method of the Collections class as the second argument of the sort method. Describe it as follows.

Collections.sort (list name, Collections.reverseOrder());

How to sort a list in ascending order:

Let’s check the sample code for sorting a list in ascending order.

package com.mycompany.javabasics;

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

/**
 *
 * @author Fawadkhan
 */
public class JavaArrayExample {

    public static void main(String[] args) {

        ArrayList<Integer> data1 = new ArrayList<>();

        data1.add(6);
        data1.add(3);
        data1.add(5);
        data1.add(1);
        data1.add(4);
        data1.add(2);

        Collections.sort(data1);

        System.out.println(data1);

    }

}

output:

Sort


How to sort a list in descending order:

Now let’s check the sample code for sorting a list in descending order.

package com.mycompany.javabasics;

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

/**
 *
 * @author Fawadkhan
 */
public class JavaArrayExample {

    public static void main(String[] args) {

        ArrayList<Integer> data1 = new ArrayList<>();

        data1.add(6);
        data1.add(3);
        data1.add(5);
        data1.add(1);
        data1.add(4);
        data1.add(2);

        Collections.sort(data1, Collections.reverseOrder());

        System.out.println(data1);

    }

}

output:

Sort

sorting List with Comparator

In the sorting methods so far, we have explained how to sort an array in ascending or descending order.

However, if you want to sort based on a specific value of a self-defined class object, or if you want to sort by more detailed conditions, what should you do?

You can achieve this by using the Comparator interface. In the sample code so far, it was possible to sort in descending order by specifying the reverseOrder method of the Collections class as the second argument of the sort method.

The reverseOrder method returns a comparator. This comparator can be custom-made with a class that implements the Comparator interface. Here is an example of creating your own comparator that sorts in descending order.


Comparator that sorts an array in descending order:

package com.mycompany.javabasics;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

/**
 *
 * @author Fawadkhan
 */
public class JavaArrayExample {

    public static void main(String[] args) {

        ArrayList<Integer> data1 = new ArrayList<>();

        data1.add(6);
        data1.add(3);
        data1.add(5);
        data1.add(2);
        data1.add(1);
        data1.add(4);

        Collections.sort(
                data1,
                new Comparator<Integer>() {
            @Override
            public int compare(Integer obj1, Integer obj2) {
                return obj2 - obj1;
            }
        }
        );

        System.out.println(data1);

    }

}

output:

Sort

This sample code implements the Comparator interface to do the same thing as the reverseOrder method. At first glance, some people may think that the amount of code just increased.

However, the method using the Comparator interface allows the programmer to decide the conditions for sorting. Use this method when you want to sort with complex conditions or rearrange objects according to specific rules.

Later we’ll show you an example of sorting objects by multiple criteria.

String Array Sorting:

Like arrays and lists of numbers, there are times when you want to sort arrays and lists of strings. In such a case, you can use the Arrays.sort method and Collections.sort method introduced so far.

When sorting the strings, they are sorted alphabetically by the first letter of the string, We will explain each method in detail.



How to use Arrays.sort to Sort String Array:

As we discussed above the Arrays.sort method is used for sorting arrays of numbers. Now in this section, I am using the same Arrays.sort method to sort the alphabetic strings.

package com.mycompany.javabasics;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

/**
 *
 * @author Fawadkhan
 */
public class JavaArrayExample {

    public static void main(String[] args) {

        String[] data1 = {" tennis ", " skateboarding ",
            " hockey ", " Badminton ",
            " cricket ", " bowling ", " Archery "};
        Arrays.sort(data1);

        System.out.println(Arrays.asList(data1));

    }

}

output:

Sort

This sample code sorts a list whose elements are alphabetical strings. You can see that the strings are sorted in alphabetical order by the first letter of the string.

How to use Collections.sort to Sort String Array

As with sorting lists of numbers, you can use Collections.sort with strings. Check the sample code.

package com.mycompany.javabasics;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

/**
 *
 * @author Fawadkhan
 */
public class JavaArrayExample {

    public static void main(String[] args) {

        ArrayList<String> data1 = new ArrayList<>();

        data1.add("tennis ");
        data1.add("skateboarding ");
        data1.add("hockey ");
        data1.add("Badminton ");
        data1.add("cricket ");
        data1.add("bowling ");
        data1.add("Archery ");

        Collections.sort(data1);

        System.out.println(data1);

    }

}

output:

Sort


sort an array by multiple keys

When sorting by multiple keys, define the sorting conditions with a unique class that implements the Comparator interface. Let’s check the sample code for sorting by person’s name and age.

package com.mycompany.javabasics;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

/**
 *
 * @author Fawadkhan
 */
class InfoClass {

    private int age;
    private String name;

    public InfoClass(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }
}

class CompClass implements Comparator<InfoClass> {

    public int compare(InfoClass c1, InfoClass c2) {
        if (c1.getAge() < c2.getAge()) {
            return -1;
        } else if (c1.getAge() > c2.getAge()) {
            return 1;
        } else {
            return c1.getName().compareTo(c2.getName());
        }
    }
}

public class JavaArrayExample {

    public static void main(String[] args) {

        ArrayList<InfoClass> data1 = new ArrayList<>();

        data1.add(new InfoClass(26, "Shaista"));
        data1.add(new InfoClass(30, "Fahad"));
        data1.add(new InfoClass(25, "Fawad khan"));
        data1.add(new InfoClass(20, "xyz"));
        data1.add(new InfoClass(16, "Abc"));
        data1.add(new InfoClass(40, "John"));

        Collections.sort(data1, new CompClass());

        for (InfoClass c : data1) {
            System.out.println("Name: " + c.getName() + ", " + "Age: " + c.getAge());

        }

    }

}

output:

Sort

In this sample code, an InfoClass class is defined that has an int type variable age and a String type variable name as members. The CompClass, the class that implements the Comparator interface defines its own comparator by specifying the InfoClass, class member name as the first key, and the member age as the second key.

By specifying this unique comparator class and sorting with the Collections.sort method, you can see that the two keys are sorted in ascending order. In the sample code, a comparison is made using the compareTo method.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button