Java sort string array alphabetically

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn java sort string array alphabetically.

Java sort string array alphabetically

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

Also read – sort string array java

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

Java program for sorting characters alphabetically in a string,

import java.util.Arrays;
public class SortString 
{
public static String stringSort(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 = stringSort(strInput);
System.out.println("Before : " + strInput);
System.out.println("After : " + strOutput);
}
}

Output:

Before : flowerbrackets
After : abceefklorrstw

Arrays.sort(T [ ], Comparator c) method

Let’s learn how to sort string using Arrays.sort(T [ ], Comparator c) method. Here given string is a mix of uppercase and lowercase characters.

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

Also read – sort string array in java – case sensitive and case insensitive

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 
{
// here 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)
{
// 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("Before sort : " + strInput);
System.out.println("After sort : " + strOutput);
}
}

Output:

Before sort : FlowerBrackets
After sort : aBceeFklorrstw

Related Posts