Sort String Array Java

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

sort string array java

Best Way 1 :

Here, in the following example I will be using Arrays.sort() method to sort an array of strings in java.

By default Arrays.sort() method sorts string in case-sensitive manner. So, to sort an array of strings irrespective of case, there is a method Arrays.sort(String[] str_Array, String.CASE_INSENSITIVE_ORDER).

Also Read – Bubble Sort Java Program

Below there are two examples, one – case-sensitive and two – case-insensitive.

Example 1 : case sensitive

import java.util.Arrays;

public class SortStringArray
{
   public static void main(String[] args)
   {
      String strPlaces[] = new String[]{"Great Barrier Reef", "paris", "bora bora", "Florence","Tokyo", "cusco"};
 
      // sorting array using sort() method
 
      Arrays.sort(strPlaces);
 
      System.out.println("Sorted array : ");
      System.out.println("\nCase Sensitive - ");
 
      // printing sorted places name
 
      for(int a = 0; a < strPlaces.length; a++)
      {
         System.out.println(strPlaces[a]);
      }
   }
}

Output:

Sorted array:

Case Sensitive –
Florence
Great Barrier Reef
Tokyo
bora bora
cusco
paris


Example 2 : case insensitive

import java.util.Arrays;

public class SortStringArray
{
   public static void main(String[] args)
   {
      String strPlaces[] = new String[]{"Great Barrier Reef", "paris", "bora bora", "Florence","Tokyo", "cusco"};

      // sorting array using sort() method

      Arrays.sort(strPlaces, String.CASE_INSENSITIVE_ORDER);

      System.out.println("Sorted array : ");
      System.out.println("\nCase Insensitive - ");

      // printing sorted places name

      for(int a = 0; a < strPlaces.length; a++)
      {
         System.out.println(strPlaces[a]);
      }
   }
}

Output:

Sorted array:

Case Insensitive –
bora bora
cusco
Florence
Great Barrier Reef
paris
Tokyo


Sort string array java

Best Way 2 : In the following example I will be using scanner class to get input from the user, that is, user will be entering string values that needs to be sorted.

Let us get into example on sort array alphabetically in java below,

import java.util.Scanner;

public class SortStringArray
{
   public static void main(String[] args)
   {
      int a;
      String toSort;
 
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter any number of strings to sort : ");
      a = sc.nextInt(); 
      String getData[] = new String[a];
 
      Scanner sc1 = new Scanner(System.in);
      System.out.println("Please enter all strings : ");
 
      for(int m = 0; m < a; m++)
      {
         getData[m] = sc1.nextLine();
      }
 
      for(int n = 0; n < a; n++)
      {
         for(int p = n + 1; p < a; p++)
         {
            if(getData[n].compareTo(getData[p]) > 0)
            {
               toSort = getData[n];
               getData[n] = getData[p];
               getData[p] = toSort;
            }
         }
      }
 
      System.out.println("Displaying sorted string : ");
      for(int x = 0; x < a - 1; x++)
      {
         System.out.print(getData[x] + " , ");
      }
 
      System.out.print(getData[a - 1]);
   }
}

Output:

sort string array java


Sort array alphabetically in java

Using to.CharArray() method we can convert string to a new character array. Then we have to apply to.CharArray() method on the given string to create a new character array.

Also Read – Java Merge Sort

In the next step we use Arrays.sort(char c[]) method to sort character array. Then we will use String class constructor to create sorted array from character array.

Here’s the example for how to sort an array alphabetically in java,

import java.util.Arrays;

public class SortString 
{
   // java sort array of strings alphabetically
   public static String stringSortJava(String strGiven)
   {
      // convert input string to char array
      char arrTemp[] = strGiven.toCharArray();

      // sort string 
      Arrays.sort(arrTemp);

      // return new sort string array
      return new String(arrTemp);
   }

   public static void main(String[] args) 
   {
      String strInput = "flowerbrackets";
      String strOutput = stringSortJava(strInput);

      System.out.println("Sorting strings in java - Before : " + strInput);
      System.out.println("Sorting strings in java - After : " + strOutput);
   }
}

Output:

Sorting strings in java – Before : flowerbrackets
Sorting strings in java – After : abceefklorrstw

NOTE:

  • In the above method we have created a new string because String is immutable in java.

Arrays.sort(T [ ], Comparator c) method – containing uppercase and lowercase character

Let’s learn sorting strings in java using Arrays.sort(T [ ], Comparator c) method. Here given string has a mix of uppercase and lowercase characters.

First we have to convert given string to character array for that we will be using for loop. Next we use Arrays.sort(T [ ], Comparator c) method to sort character array.

Also Read – Linear Search In Java

In the next step we have to implement Compare() method based on sorting operation. Lastly we use StringBuilder to convert character array to string.

import java.util.Arrays;
import java.util.Comparator;

public class StringSortJava 
{
   // this method sorts mixed string
   public static String strSort(String strInput)
   {
      // convert given string to characters in a string
      Character arrTemp[] = new Character[strInput.length()];
      for(int a = 0; a < strInput.length(); a++) 
      {
         arrTemp[a] = strInput.charAt(a);
      }

      // sorting strings in java, ignoring case
      Arrays.sort(arrTemp, new Comparator<Character>()
      {
         @Override
         public int compare(Character ch1, Character ch2)
         {
            // here in this step we are ignoring case
            return Character.compare(Character.toLowerCase(ch1), Character.toLowerCase(ch2));
         }
      });

      // converting character array to string using StringBuilder class
      StringBuilder sb = new StringBuilder(arrTemp.length);
      for(Character ch : arrTemp)
         sb.append(ch.charValue());

      return sb.toString();
   }

   public static void main(String[] args) 
   {
      String strInput = "FlowerBrackets";
      String strOutput = strSort(strInput);

      System.out.println("Sorting strings in java - Before : " + strInput);
      System.out.println("Sorting strings in java - After : " + strOutput);
   }
}

Output:

Sorting strings in java – Before : FlowerBrackets
Sorting strings in java – After : aBceeFklorrstw


Sort string array java : different arrays of primitive type

In this segment we are going to learn examples on how to sort different array of primitive type in java.

In java we have utility class java.util.Arrays which has overloaded method sort(). Using this class we will learn some examples,

For example,

static void sort(int a[]);      // sorts array parameter

In the above example function do not return anything, since the return type is void. After invoking sort() method, array passed will be modified.

Please note : that invoking above method will not create new array.

Here’s an example code,

int arrInput[] = { 4, 1, 6, 2, 8 };
Arrays.sort(arrInput);
System.out.println(Arrays.toString(arrInput));

Output : [1, 2, 4, 6, 8]

Now we will see different arrays of primitive type,

// sorting array of type byte 
byte[] byteArray = { 115, 102, 117, 12, 18 };
Arrays.sort(byteArray);

// sorting array of type char 
char[] charArray = { 'e', 'c', 'a', 'd', 'b' };
Arrays.sort(charArray);

// sorting array of type short 
short[] shortArray = { 415, 132, 600, 201, 229 };
Arrays.sort(shortArray);

// sorting array of type integer 
int[] intArray = { 4, 8, 6, 10, 2 };
Arrays.sort(intArray);

// sorting array of type long 
long[] longArray = { 15636, 526536, 653562, 231656, 325853 };
Arrays.sort(longArray);

// sorting array of type float 
float[] floatArray = { 11.5f, 21.52f, 61.45f, 29.5f, 810.14f };
Arrays.sort(floatArray);

// sorting array of type double 
double[] doubleArray = { 31.45d, 130.45d, 510.27d, 830.25d, 290.45d };
Arrays.sort(doubleArray);


How to sort portion of array using Arrays.sort() in java?

In java we can sort a portion of an array using Arrays.sort() method. Before sorting, start and end index should be specified.

Syntax :

static void sort(int[] a, int fromIndex, int toIndex)

fromIndex - (inclusive) index of the first element to be sorted.
toIndex - (exclusive) index of the last element to be sorted.

Example :

int portionArray[] = { 4, 1, 6, 5, 8, 2, 3, 10 };
Arrays.sort(portionArray, 2, 6);
System.out.println(Arrays.toString(portionArray));

Output:

[4, 1, 2, 5, 6, 8, 3, 10]

Note : In the above example index 0, 1, 6 and 7 are unchanged. Elements from index 2 to 5 are sorted.


Sort an array of objects – Arrays.sort() method

Using Arrays.sort() method we can also sort Array of objects. Now let’s see it’s syntax,

Syntax :

static void sort(Object[] a)  // sort an array of objects

Example :

String[] arrDemo = { "paris", "tokyo", "bora-bora", "florence", "cusco" };
Arrays.sort(arrDemo);
System.out.println(Arrays.toString(arrDemo));

Output:

[bora-bora, cusco, florence, paris, tokyo]


Sort an array of custom class using Arrays.sort()

In this segment we are going to learn how to sort an array of custom class using Arrays.sort().

public class Employee 
{
   String name;
   int age;

   public Employee(String name, int age) 
   {
      this.name = name;
      this.age = age;
   }
}

import java.util.Arrays;

public class SortArrayJava 
{
   public static void main(String[] args) 
   {
      Employee arrDemo[] = new Employee[5];
      arrDemo[0] = new Employee("Jackson", 6);
      arrDemo[1] = new Employee("Patrick", 3);
      arrDemo[2] = new Employee("Alfred", 14);
      arrDemo[3] = new Employee("Sam", 9);
      arrDemo[4] = new Employee("Carter", 8);
      Arrays.sort(arrDemo);
      System.out.println(Arrays.toString(arrDemo));
   }
}

Output:

Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at SortArrayJava.main(SortArrayJava.java:13)

As you can see the output of the above example ClassCastException is thrown. Because utility method does not know how to compare values of type Employee.

Now here the solution is, Employee class must implement Comparable Interface.

Here’s the code,

public class Employee implements Comparable<Employee>
{
   String name;
   int age;

   public Employee(String name, int age) 
   {
      this.name = name;
      this.age = age;
   }

   public String toString() 
   {
      return "[Employee Name : " + name + ", Employee Age : " + age + "]";
   }

   @Override
   public int compareTo(Employee em) 
   {
      return Integer.valueOf(age).compareTo(em.age);
   }
}

import java.util.Arrays;

public class SortArrayJava 
{
   public static void main(String[] args) 
   {
      Employee arrDemo[] = new Employee[5];
      arrDemo[0] = new Employee("Jackson", 6);
      arrDemo[1] = new Employee("Patrick", 3);
      arrDemo[2] = new Employee("Alfred", 14);
      arrDemo[3] = new Employee("Sam", 9);
      arrDemo[4] = new Employee("Carter", 8);
      Arrays.sort(arrDemo);
      System.out.println(Arrays.toString(arrDemo));
   }
}

Output:

[[Employee Name : Patrick, Employee Age : 3], [Employee Name : Jackson, Employee Age : 6], [Employee Name : Carter, Employee Age : 8], [Employee Name : Sam, Employee Age : 9], [Employee Name : Alfred, Employee Age : 14]]

Since in the above example we have implemented the Comparable interface, when we invoke Arrays.sort() method array will be sorted according to the age of Employee.


How to sort an array in java using custom Comparator and Arrays.sort()

Now let’s learn how to sort an array in java using custom Comparator and Arrays.sort() method.

In the previous example we sorted Employee age only. Now using Comparator we can sort an array of Employee by age and name separately. Below is the syntax,

Syntax:

public static <T> void sort(T[] a, Comparator<? super T> c)

Comparator - is a parameter that holds the logic on how to compare objects.

We can pass different Comparators depending on the requirement.

Example:

import java.util.Comparator;

public class Employee
{
   String name;
   int age;

   public Employee(String name, int age) 
   {
      this.name = name;
      this.age = age;
   }

   public String toString() 
   {
      return "[Employee name : " + name + ", Employee age : " + age + "]";
   }

   public static Comparator<Employee> AGE_COMPARATOR = new Comparator<Employee>() 
   {
      @Override
      public int compare(final Employee emp1, final Employee emp2) 
      {
         return Integer.valueOf(emp1.age).compareTo(emp2.age);
      }
   };

   public static Comparator<Employee> NAME_COMPARATOR = new Comparator<Employee>() 
   {
      @Override
      public int compare(final Employee emp1, final Employee emp2) 
      {
         return emp1.name.compareTo(emp2.name);
      }
   };
}

import java.util.Arrays;

public class SortArrayJava 
{
   public static void main(String[] args) 
   {
      Employee arrDemo[] = new Employee[5];
      arrDemo[0] = new Employee("Jackson", 6);
      arrDemo[1] = new Employee("Patrick", 3);
      arrDemo[2] = new Employee("Alfred", 14);
      arrDemo[3] = new Employee("Sam", 9);
      arrDemo[4] = new Employee("Carter", 8);
      System.out.println("Sorting an array in java by Employee name : ");
      Arrays.sort(arrDemo, Employee.NAME_COMPARATOR); 
      System.out.println(Arrays.toString(arrDemo));
      System.out.println("Sorting an array in java by Employee age : ");
      Arrays.sort(arrDemo, Employee.AGE_COMPARATOR); 
      System.out.println(Arrays.toString(arrDemo));
   }
}

Output:

Sorting an array in java by Employee name :
[[Employee name : Alfred, Employee age : 14], [Employee name : Carter, Employee age : 8], [Employee name : Jackson, Employee age : 6], [Employee name : Patrick, Employee age : 3], [Employee name : Sam, Employee age : 9]]

Sorting an array in java by Employee age :
[[Employee name : Patrick, Employee age : 3], [Employee name : Jackson, Employee age : 6], [Employee name : Carter, Employee age : 8], [Employee name : Sam, Employee age : 9], [Employee name : Alfred, Employee age : 14]]


Sorting an array in java in descending order using Arrays.sort()

Now let’s learn java sort array in descending order using Arrays.sort(). By default Arrays.sort() method sorts array in ascending order.

To sort array in descending order in java we reverse the result after sorting using reverse() method.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortArrayDescending 
{
   public static void main(String[] args) 
   {
      Integer arrDesc[] = { 4, 1, 6, 2, 8 };
      Arrays.sort(arrDesc);
      List<Integer> li = Arrays.asList(arrDesc);
      Collections.reverse(li);
      li.toArray(arrDesc);
      System.out.println("Java sort array in descending order : " + Arrays.toString(arrDesc));
   }
}

Output:

Java sort array in descending order : [8, 6, 4, 2, 1]


Another way : To sort array in java in descending order

Using custom comparator we can sort array in java in descending order.

import java.util.Arrays;
import java.util.Comparator;

public class SortDescending 
{
   public static void main(String[] args) 
   {
      Integer arrDesc[] = { 4, 1, 6, 2, 8 };
      Arrays.sort(arrDesc, new Comparator<Integer>()
      {
         @Override
         public int compare(Integer arg0, Integer arg1) 
         {
            return -1 * arg0.compareTo(arg1);    // logic is reversed here by multiplying the result of compareTo with -1
         }});
         System.out.println("Java sort array in descending order : " + Arrays.toString(arrDesc));
   }
}

Output :

Java sort array in descending order : [8, 6, 4, 2, 1]


Sort array in java without invoking any predefined methods,

import java.util.Arrays;

public class SortArrayStrings 
{
   public static void sortArray(Integer[] arrInt) 
   {
      int b = 0;
      Integer temp;
      boolean sort = false;
      while(!sort) 
      {
         sort = true;
         b++;
         for(int a = 0; a < arrInt.length - b; a++) 
         {
            if(arrInt[a].compareTo(arrInt[a + 1]) > 0) 
            {
               temp = arrInt[a];
               arrInt[a] = arrInt[a + 1];
               arrInt[a + 1] = temp;
               sort = false;
            }
         }
      }
   }

   public static void main(String[] args) 
   {
      Integer[] myArray = { 4, 1, 6, 2, 8 };
      sortArray(myArray);
      System.out.println("Sorting an array in java : " + Arrays.toString(myArray));
   }
}

Output:

Sorting an array in java : [1, 2, 4, 6, 8]


conclusion

That’s it guys. This is all about sort string array java, how to sort an array alphabetically in java and sort array in descending order in java.

I hope you guys have understood the concept of sort string array in java. You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

Related Posts