How to sort a String array in Java?



To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.

One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.

Example

Live Demo

import java.util.Arrays;

public class StringArrayInOrder {
   public static void main(String args[]) {
      String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop", "Neo4j"};
      int size = myArray.length;

      for(int i = 0; i<size-1; i++) {
         for (int j = i+1; j<myArray.length; j++) {
            if(myArray[i].compareTo(myArray[j])>0) {
               String temp = myArray[i];
               myArray[i] = myArray[j];
               myArray[j] = temp;
            }
         }
      }
      System.out.println(Arrays.toString(myArray));
   }
}

Output

[HBase, Hadoop, Java, JavaFX, Neo4j, OpenCV]

You can also sort an array using the sort() method of the Arrays class.

String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop","Neo4j"};
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));
Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician


Advertisements