Two Best Ways In Java To Sort String Array

Sharing is healthy !!

You are here to learn two best ways in java to sort string array.

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).

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

Example 1: case sensitive

Also Read – Bubble Sort Java Program

import java.util.Arrays;

public class Sort_String_Array {

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

public static void main(String[] args) {

String str_Places[] = new String[]{"Great Barrier Reef", "paris", "bora bora", "Florence","Tokyo", "cusco"};

// sorting array using sort() method

Arrays.sort(str_Places, String.CASE_INSENSITIVE_ORDER);

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

// printing sorted places name

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

Output:

Sorted array:

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


Two Best Ways In Java To Sort String Array

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 below,

Also Read – Java Merge Sort

import java.util.Scanner;

public class Sort_String_Array {

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

Output:

Two Best Ways In Java To Sort String Array

Sharing is healthy !!