Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Sort Array Elements


How to sort a String type Array in Ascending Order?


The Sort() method is used to sort a String Array in Ascending order.


Example :



import java.util.Arrays;

public class MyApplication {
    public static void main(String[] args) {

        String[] arr = {"Mohan", "John", "Paul", "Kriti", "Salim"};
        Arrays.sort(arr);

        System.out.println("The Sorted Array in ascending order is : ");

        for (String str : arr) {
            System.out.println(str);
        }
    }
}


Output :



  The Sorted Array in ascending order is :
  John
  Kriti
  Mohan
  Paul
  Salim

So, in the above code we have created a Array and initialised to the variable arr.


String[] arr = {"Mohan", "John", "Paul", "Kriti", "Salim"};

Below is how the values are positioned in the Array,

Spring_Boot

Then we have used the Arrays.sort(arr) method to sort the Array arr in ascending order.


Arrays.sort(arr);

And the Array arr gets sorted with John as the first value, Kriti second and Mohan as the third, Paul as fourth and Salim as the fifth value.

Spring_Boot

And we get the below output.

Output :



  The Sorted Array in ascending order is :
  John
  Kriti
  Mohan
  Paul
  Salim

How to sort a Array with numbers in Increasing Order?


Even here the sort() method is used to sort the numbers in Increasing Order.


Example :



import java.util.Arrays;

public class MyApplication
{
    public static void main(String[] args)
    {
        int[] arr = {5, 3, 2, 4};
        Arrays.sort(arr);
    
        System.out.println("The Sorted Array in ascending order is : ");
    
        for (int str : arr) {
            System.out.println(str);
        }
    }    
}


Output :



  The Sorted Array in ascending order is :
  2
  3
  4
  5

So, in the above code we have created an Integer Array and initialised to the variable arr.


int[] arr = {5, 3, 2, 4};

Below is how the values are positioned in the Array,

Spring_Boot

Then we have used the sort() Method from the java.util package to sort the Array arr in increasing order.


Arrays.sort(arr);

And the numbers in the Array arr gets sorted.

Spring_Boot

And we get the below output.

Output :



  The Sorted Array in ascending order is :
  2
  3
  4
  5