![]() |
VOOZH | about |
To sort the array of objects in both ascending and descending order in Java, we can use the Arrays.sort() method with the Comparator. In this article, we will learn how to sort an array of objects using Arrays.sort().
With Array of Object what it really means is an array storing any type of object can be Integer, String or User Defined. Let us check it with an example mentioned below:
Input : { { Bob ,25 } , { Charlie , 35 } , { Alice , 30} }
Output:
Sorting Objects according to age : { { Bob , 25 } , { Alice , 30} , { Charlie , 35 } }
Sorting Objects according to name : { { Alice , 30} , { Bob ,25 } , { Charlie , 35 } }
Below is the example using the custom Person class and sorting an array in both ascendingorder and descendingorder.
Output:
Ascending order by age: [Bob (25), Alice (30), Charlie (35)]
Descending order by age: [Charlie (35), Alice (30), Bob (25)]
Ascending order by name: [Alice (30), Bob (25), Charlie (35)]
Descending order by name: [Charlie (35), Bob (25), Alice (30)]
Explanation of above program: