sort array in java

Previous
Next

In this post, we will see how to sort an array in java.

There are various ways to sort array in java. You can implement different sorting algorithms to sort an array.

You can use Arrays.sort method to sort array in java. There are various overloaded versions of Arrays.sort method. You can go through it over here.

Java Sort Array

Let’s see some example to sort an array in java.

Sort Array of numbers

Sorting an array of numbers is very easy. You just need to use Array.sort method to sort array of numbers.

When you run above code, you will get below output:

Before Sorting
===============
7 33 22 11 20 5 2
===============
After Sorting
===============
2 5 7 11 20 22 33

Sort Array of Strings

Sorting an array of String is also very easy. You just need to use Array.sort method to sort array of Strings.This will sort array of String in ascending order.

When you run above code, you will get below output:

Before Sorting
===============
Martin Andy John Mary
===============
After Sorting
===============
Andy John Martin Mary

Sort array of custom objects

For Sorting array of custom objects, Custom object should implement comparable interface and then pass it to Array.sort method.You can also create comparator object and pass it to Array.sort method.

When you run above code, you will get below output:

Before Sorting
===============
[ name=Martin age=20 ] [ name=Andy age=18 ] [ name=John age=22 ] [ name=Mary age=21 ]
===============
After Sorting
===============
[ name=Andy age=18 ] [ name=John age=22 ] [ name=Martin age=20 ] [ name=Mary age=21 ]

That’s all about Sorting an array in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog