- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort arrays of objects in Java
An array of objects can be sorted using the java.util.Arrays.sort() method with a single argument required i.e. the array to be sorted. A program that demonstrates this is given as follows −
Example
import java.util.Arrays; public class Demo { public static void main(String args[]) throws Exception { String str[] = new String[]{"apple","orange","mango","guava", "melon"}; int n = str.length; System.out.println("The original array of strings is: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } Arrays.sort(str); System.out.println("The sorted array of strings is: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } } }
Output
The original array of strings is −
apple orange mango guava melon The sorted array of strings is: apple guava mango melon orange
Now let us understand the above program.
First the string array str is defined and then printed using for loop. A code snippet which demonstrates this is as follows −
String str[] = new String[]{"apple","orange","mango","guava", "melon"}; int n = str.length; System.out.println("The original array of strings is: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); }
Then the Arrays.sort() method is used to sort str. Then the resultant sorted string array is displayed using for loop. A code snippet which demonstrates this is as follows −
Arrays.sort(str); System.out.println("The sorted array of strings is: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); }
Advertisements