Sorting of an array in java | Sorting array in java using comparator

preview_player
Показать описание
Do you want to explore how can we sort an array elements in the Java? You’re at the at right place. Please watch this video till end we’re first going to sort the array of strings then we’ll see see how we can sort the array of objects. So please sit tight & lets get started

Let us first create class with main method. Create array of string containing names. Now hit the sort method of the Arrays class. We need to import the Arrays class using import statement.

If you want to sort the array of string in descending order then we have to use the reverseOrder() method of collections class. Sorting of the such array having string is pretty simple but if you want to sort the array of objects then we’ve to use the Comparator interface.

Let’s first create the class with name Person. We’re going to add the two fields name and age. Let me generate the gets and sets along with toString() method. Create array of person objects with name Persons. Now we want to sort the Persons array by name then by age.

For this we’ve to create the another class by implementing the Comparator interface. Comparator interface has one method called compare() method. We’ve to override this method and put the logic for the sorting.

Java doc of Arrays class can be found using following link:

Java doc of Collections class can be found using following link:

Java doc of the Comparator Interface can be found using following link:

Link to download the Java:

If you like this video, please checkout other such videos:

Рекомендации по теме
Комментарии
Автор

Looking from a long time for proper explanation of this. Literally it is very useful for me. Thankx

chitratejuja
Автор

Great tutorial. I now know how to use the comparator. Thank you.

dalitsobotha
Автор

Good One. Please create the video to sort an array of complex objects

radhasoamibeas
Автор

It is possible at your end so show case all methods of "Arrays" class. Would be great if you can show us the use of "Comparator" interface with more examples

keshavtejuja
Автор

I like your program "Sorting array in java using comparator". Thanks for sharing this Java Tutorial Video.

dipakahuja
Автор

Also wanted to see the examples of multidimensional arrays in Java

keshavtejuja
Автор

One more video for Sorting of an array in java

giritejuja
Автор

I was looking for sorting of array in reverse order using Java. Can you please explain collections class in detail?

krishnatalreja
Автор

Can we sort array of integers through Arrays.sort()?

Liamlefe