AppDividend
Latest Code Tutorials

Sorting in Java Example | Java Sorting Tutorial

0

Sorting in Java Example | Java Sorting Tutorial is today’s topic. Sorting refers to the act of arranging the objects in a particular order, be it ascending or descending order. In java, we have predefined methods for sorting the objects. For sorting an array of objects/primitive data types, java defined a method Arrays.sort(). Whereas while working on the List collections in java (like LinkedList, Queue, ArrayList, etc.), we have a method Collections.sort(). Both of the methods sort the object in the ascending order by default. If we want to sort the objects in the descending order, we can use the method Collections.reverseOrder().

Sorting in Java

See the following figure.

Sorting in Java Example

The Arrays.sort() method is defined in the java.util.Arrays package. This method uses different sorting algorithms in different situations. For the array of objects it uses merge sort, while when the array is composed of primitive datatypes, it uses quicksort.

See the following syntax.

public static void sort(Object[ ] arr, int start, int end)

Since the return type of this method is void, it does not return anything. arr specifies the array on which we want to apply the sort method. Start tells the starting index from which we want to sort, and end specifies the index up to which we want to perform sort (end excluded). The start and end arguments are given only when we do not want to sort the whole array and instead we want a subarray to get sorted. There are several overloaded versions of the Arrays.sort() method. They are listed below:

public static void sort(Object[] arr)
public static void sort(byte[] arr, int start, int end)
public static void sort(byte[] arr)
public static void sort(short[] arr, int start, int end)
public static void sort(short[] arr)
public static void sort(int[] arr, int start, int end)
public static void sort(int[] arr)
public static void sort(long[] arr, int start, int end)
public static void sort(long[] arr)
public static void sort(double[] arr, int start, int end)
public static void sort(double[] arr)
public static void sort(float[] arr, int start, int end)
public static void sort(float[] arr)
public static void sort(char[] arr, int start, int end)
public static void sort(char[] arr)
public static void sort(String[] arr, int start, int end)
public static void sort(String[] arr)

It is also possible to sort an array using a comparator.

public static void sort(T[] arr, Comparator<? super T> comp)
public static void sort(T[] arr, int start, int end, Comparator<? super T> comp)

The Collections.sort() method is defined in the java.util.Collections package. It is used to sort the List collections likes LinkedList, Queue, ArrayList, etc. by arranging the objects of the collection in the ascending order.

#Syntax

public static<T extends Comparable<? super T>> void sort(List<T> l)

This method will sort the elements of the List based on the natural ordering of the elements. T specifies the type of list elements. The l specifies the list to be sorted.

public static<T> void sort(List<T> l, Comparator<? super T> comp)

This method will sort the elements of list l according to the specified Comparator comp.

See the following programs.

Example1.java: Sort an array of strings in ascending and descending order.

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

class Example1 {
  public static void main(String[] args) {
    // creating an array of strings
    String[] name = { "Raghu", "Vijay", "Virat", "Akash", "Sonal" };
    System.out.print("Original Array: ");
    for (String s : name)
      System.out.print(s + " ");

    // sorting the array in ascending order
    Arrays.sort(name);
    System.out.print("\nSorted array in ascending order: ");
    for (String s : name)
      System.out.print(s + " ");

    // sorting the array in the descending order using Collections.reverseOrder()
    Arrays.sort(name, Collections.reverseOrder());
    System.out.print("\nSorted array in Descending order: ");
    for (String s : name)
      System.out.print(s + " ");

    System.out.println();
  }
}

See the following output.

 

Java Sorting Tutorial

Example2.java: Sort an ArrayList using the Collections.sort() method.

import java.util.*;

class Example2 {
  public static void main(String[] args) {
    // Cretaing an arraylist to be sorted
    ArrayList<Integer> arr = new ArrayList<Integer>();
    arr.add(35);
    arr.add(7);
    arr.add(28);
    arr.add(14);
    arr.add(21);
    System.out.println("Original ArrayList: " + arr);

    // sorting the arraylist
    Collections.sort(arr);
    System.out.println("Sorted ArrayList: " + arr);
  }
}

See the following output.

 

Java Sorting Example

Example3.java: Sort an ArrayList of Strings using a Comparator, based on the length of the strings.

import java.util.*;

class StrLen implements Comparator<String> {
  // Comaprator to compare 2 strings by their length
  public int compare(String s1, String s2) {
    return s1.length() - s2.length();
  }
}

public class Example3 {
  public static void main(String[] args) {
    // Creating an ArrayList of names
    ArrayList<String> name = new ArrayList<String>();
    name.add("Abhishek");
    name.add("Monisha");
    name.add("Akash");
    name.add("Aparshakti");
    name.add("Pranshu");

    System.out.println("Original List: " + name);

    // Sorting ArrayList using comparator StrLen and sort them in the ascending
    // order of their length
    Collections.sort(name, new StrLen());
    System.out.println("Sorted List: " + name);
  }
}

See the following output.

 

Java Sorting Tutorial Example

Finally, Sorting in Java Example | Java Sorting Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.