Sort arrays of objects in Java

Java 8Object Oriented ProgrammingProgramming

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]);
}
raja
Published on 09-Jan-2019 10:13:54
Advertisements