Java Sort Array

Hi guys!! Welcome to flower brackets blog. In this post we are going to learn java sort array.

java sort array

We can use java arrays.sort method to sort elements in an array. Either it might be ascending or descending order.

Java sort array

arrays.sort method can be found in java.util.Arrays class.

arrays.sort() syntax:

public static void sort(int[] arr, int from_Index, int to_Index)

arr - array to be sorted
from_Index - index of the first element to be sorted, inclusive.
to_Index - index of the last element to be sorted, exclusive.

sort() method will not return any value.

We can do both sorting in ascending and descending using arrays.sort method. Here’s the example on sort array in ascending order java using arrays.sort method,

import java.util.Arrays;

public class JavaSort 
{
   public static void main(String[] args) 
   {		
      int arrNum[] = {14, 5, 8, 23, 100, 85};
 
      Arrays.sort(arrNum); // arrays.sort method by default sorts in ascending order

      // sort array in ascending order java 
      System.out.printf("Sorted array java : %s", Arrays.toString(arrNum));
   }
}

Output :

Sorted array java : [5, 8, 14, 23, 85, 100]


Now let’s learn how to sort a subarray in java using arrays.sort. Here’s the example,

import java.util.Arrays;

public class SortJava 
{
   public static void main(String[] args) 
   { 
      int arrDemo[] = {14, 8, 5, 54, 41, 10, 1, 500};

      // here we are sorting subarray elements only i.e, {8, 5, 54, 41} 
      Arrays.sort(arrDemo, 1, 5);

      System.out.printf("Sorted array java : %s", Arrays.toString(arrDemo));
   }
}

Output :

Sorted array java : [14, 5, 8, 41, 54, 10, 1, 500]


Next, using the same example we are sorting in descending order in java using arrays.sort. Here’s an example on how to sort array in descending order in java,

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

public class JavaArraySort 
{
   public static void main(String[] args) 
   {
      Integer arrNum[] = {14, 8, 5, 54, 41, 10, 1, 500};

      // java array sort descending
      Arrays.sort(arrNum, Collections.reverseOrder());

      System.out.printf("Sorted array java : %s", Arrays.toString(arrNum));
   }
}

Output :

Sorted array java : [500, 54, 41, 14, 10, 8, 5, 1]


Example : java sort array

Now we will see how to print strings in descending order. So in order to print strings in the descending order, same method is used as above.

Also Read – Sort String Array Java

That is arrays.sort. But earlier we used only simple sort method which accepts string array.

Now it accepts comparator to print values in reverse or descending order. So we need to call the utility method in collections class which is reverseOrder().

Here’s the example,

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

public class ArraySortAscending
{
   public static void main(String[] args)
   {
      String strAsc[] = {"Bear","Fox","Deer","Cheetah","Anteater","Elephant"}; 

      System.out.println("Before sorting: ");
      for(String string : strAsc)
      {
         System.out.println(string);
      }

      Arrays.sort(strAsc,Collections.reverseOrder());   
      System.out.println("-----------------------------------");
  
      System.out.println("After sorting: ");
      for(String string : strAsc)
      {
         System.out.println(string);
      }
   }
}

Output :

Before sorting:
Bear
Fox
Deer
Cheetah
Anteater
Elephant
———————————–
After sorting:
Fox
Elephant
Deer
Cheetah
Bear
Anteater


Now we will use the same example to sort array in ascending order,

import java.util.Arrays;

public class ArrayIntegerDemo 
{
   public static void main(String[] args)
   {
      String arrString[] = {"Bear", "Fox", "Deer", "Cheetah", "Anteater", "Elephant"};

      // sorting array in java in ascending order
      Arrays.sort(arrString);
      System.out.printf("Sorted array java : %s", Arrays.toString(arrString)); 
   }
}

Output :

Sorted array java : [Anteater, Bear, Cheetah, Deer, Elephant, Fox]


Arrays.sort java comparator

Using array.sort java comparator we can sort an array according to particular criteria. Here Comparator interface is used to sort array,

import java.util.Comparator;

// Student class
public class Student 
{
   int ID; 
   String name, city; 

   // this is student constructor 
   public Student(int ID, String name, String city) 
   { 
      this.ID = ID; 
      this.name = name; 
      this.city = city; 
   } 

   // here we are printing student details in main method 
   public String toString() 
   { 
      return this.ID + " " + this.name + " " + this.city; 
   } 
} 

// java sort array comparator
class SortbyID implements Comparator<Student> 
{ 
   // here we are sorting in ascending order of ID 
   public int compare(Student A, Student B) 
   { 
      return A.ID - B.ID; 
   }
}

// main method

import java.util.Arrays;

public class ArraySortDemo 
{
   public static void main(String[] args) 
   {
      Student tutee[] = { new Student(103, "Chris", "New Jersey"), 
                          new Student(101, "Kerb", "Texas"), 
                          new Student(102, "John", "Carolina")};

      System.out.println("Unsorted array : "); 
      for(int a = 0; a < tutee.length; a++) 
         System.out.println(tutee[a]);

      Arrays.sort(tutee, new SortbyID());

      System.out.println("\nArrays.sort java - sorted by ID : "); 
      for(int a = 0; a < tutee.length; a++) 
         System.out.println(tutee[a]); 
   }
}

Output :

Unsorted array :
103 Chris New Jersey
101 Kerb Texas
102 John Carolina

Arrays.sort java – sorted by ID :
101 Kerb Texas
102 John Carolina
103 Chris New Jersey


parallelSort in Java 8

So earlier for sorting we were using different types algorithms, using comparable, different APIs and logics to sort an array.

Now Java 8 provides new API in new classes with different methods.

Parallel array sorting is used to sort array elements in parallel fashion and finally merged as a sorted array. Java 8 has a new API called parallelSort.

Syntax :

Arrays.parallelSort(int a[], int fromIndex, int toIndex);

New methods has been added to java.util.Arrays package. parallelSort method is overloaded for all primitive data types and comparable objects.

Basically parallelSort method breaks array into different sub-arrays. Each sub-array is sorted with arrays.sort in different threads.

Now here’s an example on sorting an array in java using parallelSort method,

import java.util.Arrays;

public class JavaSortExample 
{
   public static void main(String[] args) 
   {
      int numbers[] = {80, 40, 50, 30, 10, 70, 20};
      for(int a : numbers)
      {
         System.out.print(a + " ");
      }
      Arrays.parallelSort(numbers, 1, 5);
      System.out.println("\nAfter sorting an array in java : ");
      for(int a : numbers)
      {
         System.out.println(a + " ");
      }
   }
}

Output :

80 40 50 30 10 70 20
After sorting an array in java :
80
10
30
40
50
70
20


Java list sorting example

Now we are going to use Collections.sort API to sort a list in java. We can find this API in java.utils.Collections package.

Here’s java list sorting example,

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortListExample 
{
   public static void main(String[] args) 
   {
      List<Integer> num = new ArrayList<Integer>();
      num.add(80);
      num.add(40);
      num.add(50);
      num.add(30);
      num.add(10);
      num.add(70);
      num.add(20);
      System.out.println("Before java list sort : ");
      for(int a : num)
      {
         System.out.println(a);
      }

      Collections.sort(num);
      System.out.println("After java list sort : ");
      for(int a : num)
      {
         System.out.println(a);
      }
   }
}

Output :

Before java list sort :
80
40
50
30
10
70
20
After java list sort :
10
20
30
40
50
70
80


Sorting map in java based on keys and values

Now we are going to sort map based on keys and values. Here’s an example on java map sorting example,

import java.text.ParseException; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.HashMap; 
import java.util.LinkedHashMap; 
import java.util.List; 
import java.util.Map.Entry; 
import java.util.Set; 
import java.util.TreeMap; 

public class HashMapSortDemo
{ 
   public static void main(String args[]) throws ParseException
   { 
      // creating a map with SQL releases and their code names 
      HashMap<String, String> releases = new HashMap<String, String>(); 
      releases.put("SQL Server 6.0", "SQL95"); 
      releases.put("SQL Server 1.1", "Pietro"); 
      releases.put("SQL Server 1.0", "Filipi"); 
      releases.put("SQL Server 6.5", "Hydra"); 
      releases.put("SQL Server 7.0", "Sphinx"); 

      System.out.println("Before sorting hashmap : "); 

      Set<Entry<String, String>> setEntry = releases.entrySet(); 
      for(Entry<String, String> entry : setEntry)
      {
         System.out.println(entry.getKey() + " ==> " + entry.getValue()); 
      }
      System.out.println("\n");

      // let's sort HashMap by key. For that we need to
      // create a TreeMap with mappings of HashMap.
      // Here TreeMap keeps all entries in sorted order 

      TreeMap<String, String> tmSorted = new TreeMap<>(releases); 
      Set<Entry<String, String>> mappings = tmSorted.entrySet(); 
      System.out.println("After sorting hashmap by key java in ascending order : "); 
      for(Entry<String, String> mapping : mappings)
      {
         System.out.println(mapping.getKey() + " ==> " + mapping.getValue()); 
      }
      System.out.println("\n");

      // let's sort HashMap by value. For that there is no direct way
      // to sort HashMap by value. You can do that using comparator 
      // which takes Map.Entry object and arrange them in order increasing
      // or decreasing by values. 

      Comparator<Entry<String, String>> valueComparator = new Comparator<Entry<String,String>>() 
      {
         @Override 
         public int compare(Entry<String, String> e1, Entry<String, String> e2) 
         {
            String v1 = e1.getValue(); String v2 = e2.getValue(); 
            return v1.compareTo(v2); 
         }
      };
      // here we are converting Set to List. Because sort method needs a list 
      List<Entry<String, String>> listOfEntries = new ArrayList<Entry<String, String>>(setEntry); 
      // sorting HashMap by value java using comparator 
      Collections.sort(listOfEntries, valueComparator); 
      LinkedHashMap<String, String> sortedByValue = new LinkedHashMap<String, String>(listOfEntries.size()); 
      // here we are copying entries from List to Map 
      for(Entry<String, String> entry : listOfEntries)
      {
         sortedByValue.put(entry.getKey(), entry.getValue()); 
      }
      System.out.println("After sorting HashMap by value java : "); 
      Set<Entry<String, String>> entrySortedByValue = sortedByValue.entrySet(); 
      for(Entry<String, String> mapping : entrySortedByValue)
      {
         System.out.println(mapping.getKey() + " ==> " + mapping.getValue()); 
      }
   }
}

Output :

Before sorting hashmap :
SQL Server 6.5 ==> Hydra
SQL Server 6.0 ==> SQL95
SQL Server 7.0 ==> Sphinx
SQL Server 1.0 ==> Filipi
SQL Server 1.1 ==> Pietro

After sorting hashmap by key java in ascending order :
SQL Server 1.0 ==> Filipi
SQL Server 1.1 ==> Pietro
SQL Server 6.0 ==> SQL95
SQL Server 6.5 ==> Hydra
SQL Server 7.0 ==> Sphinx

After sorting HashMap by value java :
SQL Server 1.0 ==> Filipi
SQL Server 6.5 ==> Hydra
SQL Server 1.1 ==> Pietro
SQL Server 6.0 ==> SQL95
SQL Server 7.0 ==> Sphinx


conclusion:

Well that’s it. This is all about how to sort elements in array in ascending order in java. You can subscribe to my blog flower brackets if you haven’t.

If you find this post useful share it across social networks.

Related Posts