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

 Live Demo

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]);
}

Updated on: 25-Jun-2020

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements