How to sort an array of objects in java ascending or descending order

HQ ┬╗ Java Tutorial ┬╗ Example Source Code ┬╗ Java Array Examples ┬╗ How to sort an array of objects in java ascending or descending order
How to sort an array of objects in java ascending or descending order 2018-02-16T07:27:55+00:00

Sorting an array is an easy task in java especially if its in natural order or should we say in ascending order. This java tutorial is very helpful in designing a real life java applications. Complete java array example source code is provided below which you can modify for your own personal use. How to sort an array in ascending order is very easy however in descending order, we need to use a more complicated API.

Instructions in sorting an array of objects in Java

Consider an array of string objects “one”, “two”, “three”. Sort it out using java API in ascending and descending order. Print on the console the initial contents of the array, ascending order, and descending order.

Java API that is used in this example

java.util.Arrays class is a member of the Java Collections Framework

  • sort(Objects
    [] obj) – this method sort the array of objects in natural order
  • sort(Objects[] obj,Comparator c) – specified array of objects were sorted out using the specified comparator

java.util.Collections is also a member of the Java Collections Framework which we needed for the sorting

  • reverseOrder() – this method of the Collections class returns a comparator that implements a reverse of the natural ordering of a collections of objects which in this case its an array of String.

Sort an Array Example Source code

Sample Console Output using eclipse for java

Toggle Sliding Bar Area

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close