How To Sort Elements In Array In Ascending Order In Java

Sharing is healthy !!

Hi guys!! Welcome to flower brackets. In this post we are going to learn how to sort elements in array in ascending order in java.

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

We can do both sorting in ascending and descending using arrays.sort method.

example: How To Sort Elements In Array In Ascending Order In Java

import java.util.Arrays;

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);
System.out.println("-----------------------------------"); System.out.println("After sorting: ");
for(String string : strAsc)
{
System.out.println(string);
}
}
}

Output:

How To Sort Elements In Array In Ascending Order In Java


example: How To Sort Elements In Array In descending Order In Java

Now what I will do, I need to print the elements in descending order. So in order to print the elements in the descending order, same method is used as above.

Also Read – Two Best Ways In Java To Sort String Array

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 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:

How To Sort Elements In Array In Ascending Order In Java


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 if you haven’t.

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

Sharing is healthy !!