Sort string array java

Hey guys!!! Welcome to flower brackets blog. You are here to learn sort string array java.

sort string array java

Basically in string class we do not have method that sorts a string directly. To sort string array we can use other methods.

In java, to sort a string we need to match each element of an array to the remaining elements. Then, if result is > 0 we have to swap them.

Also read – sort string array case sensitive and case insensitive

To do that let’s see a java program using nested for loop. In this nested for loop, inner loop starts with a + 1, where “a” is the variable of outer for loop.

import java.util.Arrays;

public class SortStringArrayDemo
{
   public static void main(String[] args) 
   { 
      String strPlaces[] = {"Great Barrier Reef", "Paris", "BoraBora", "Florence","Tokyo", "Cusco"};
      int size = strPlaces.length;
      for(int a = 0; a < size - 1; a++) 
      {
         for(int b = a + 1; b < strPlaces.length; b++) 
         {
            if(strPlaces[a].compareTo(strPlaces[b]) > 0) 
            {
               String temp = strPlaces[a];
               strPlaces[a] = strPlaces[b];
               strPlaces[b] = temp;
            }
         }
      }
      System.out.println(Arrays.toString(strPlaces));
   }
}

Output:

[BoraBora, Cusco, Florence, Great Barrier Reef, Paris, Tokyo]


Using sort() method

Also read – sort string array in java alphabetically

import java.util.Arrays;

public class JavaArraySort
{
public static void main(String[] args)
{
String strGiven[] = {"Great Barrier Reef", "Paris", "BoraBora", "Florence","Tokyo", "Cusco"};
Arrays.sort(strGiven);
System.out.println("Output : " + Arrays.toString(strGiven));
}
}

Output:

Output : [BoraBora, Cusco, Florence, Great Barrier Reef, Paris, Tokyo]

Also read – java sort both primitive and object array

Related Posts