Java Sort Array of Strings

Sorting means arranging the elements in a particular way i.e, it can either be in an increasing or decreasing order. In the case of strings if I want to sort all the elements in increasing order it means the lexicographically smallest element will come first. There are many popular sorting algorithms that can be used to sort elements. For example bubble sort, selection sort, insertion sort, and more.

In this blog, we will see predefined methods and user-defined methods as well to sort an array consisting of strings.

Using Inbuilt Method

Predefined methods are basically those methods that are already defined in the java class libraries. Therefore we can import them from libraries and directly call them.

So there is already a sort() method defined inside the Array class and if we import java.util.Arrays this method can be called.

Let us check out one code example to sort strings inside the array in ascending order with the use of a predefined method.

import java.util.*;

public class sortarrofstr {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Please Enter the total number of persons in your family: ");
		int n = sc.nextInt();
		String names[] = new String[n];
		System.out.println("Please Enter names of all the persons in your family: ");
		for(int i=0 ;i<n; i++) {
			names[i] = sc.next();
		}

		Arrays.sort(names);  
		System.out.println("The names sorted in ascending order are printed below: ");
		for(int i=0; i<n; i++) {
			System.out.print(names[i]+" ");
		}
		System.out.println();
	}

}

Output:

Please Enter the total number of persons in your family:
4
Please Enter names of all the persons in your family:
ram
mohan
lata
shriya
The names sorted in ascending order are printed below:
lata mohan ram shriya

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we create an object of the Scanner class which helps us to take input. Now we are asking for the input of the total number of persons present inside the array. After this, we will input all the names of the persons as strings and store them inside the names array. Now, the most important line in the code comes where we use the sort() function to sort the array elements in ascending order. Finally, all the sorted array elements are printed one after another.

What if the array of Strings needs to be sorted in descending order?

To sort an array of strings in descending order we can use the Collections class present in java. A reverseOrder() method is present inside the collections class which mainly returns the comparator imposing natural ordering. Let us see a short example of this below.

import java.util.*;

public class sortarrofstr {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println( "Please Enter the total number of persons in your family: " );
		int n = sc.nextInt();
		String names[] = new String[n];
		System.out.println( "Please Enter names of all the persons in your family: " );
		for(int i=0; i<n; i++) {
			names[i] = sc.next();
		}

		Arrays.sort(names, Collections.reverseOrder());  
		System.out.println( "The names sorted in ascending order are printed below: " );
		for(int i=0; i<n; i++) {
			System.out.print(names[i]+" ");
		}
		System.out.println();
	}

}

Output:

Please Enter the total number of persons in your family:
3
Please Enter names of all the persons in your family:
neha
adi
mukesh
The names sorted in ascending order are printed below:
neha mukesh adi

Explanation:

This code is almost similar to our 1st code except for one line where we are calling Arrays.sort(names, Collections.reverseOrder()). Here this reverseOrder method is responsible for the output in descending order.

Using Userdefined Method

As the name suggests, the user-defined methods are declared by the user. These methods can be changed according to the needs of the user. Furthermore, these methods can be declared public or private depending upon the security of the code required.

Let us check out one code example to sort strings inside the array in ascending order with the use of a userdefined method.

import java.util.*;

public class sortarrofstr {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println( "Please Enter the total number of persons in your family: " );
		int n = sc.nextInt();
		String names[] = new String[n];
		System.out.println( "Please Enter names of all the persons in your family: " );
		for(int i=0; i<n; i++) {
			names[i] = sc.next();
		}

		for(int i = 0; i<n; i++) {  
			for (int j = i+1; j<n; j++) {    
				if(names[i].compareTo(names[j]) > 0) {   
					String temp = names[i];  
					names[i] = names[j];  
					names[j] = temp;  
				}  
			}  
		}    
		System.out.println( "The names sorted in ascending order are printed below: " );
		for(int i=0;i<n;i++) {
			System.out.print(names[i]+" ");
		}
		System.out.println();
	}

}

Output:

Please Enter the total number of persons in your family:
5
Please Enter names of all the persons in your family:
neeraj
aditya
suresh
neha
mayank
The names sorted in ascending order are printed below:
aditya mayank neeraj neha suresh

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we create an object of the Scanner class which helps us to take input. Now we are asking for the input of the total number of persons present inside the array. After this, we will input all the names of the persons as strings and store them inside the names array.

Now we will run a loop for all the names and a nested loop will run inside this loop where the comparison of both the strings is done. If the string coming before is lexicographically greater than the string coming after then both of them are swapped using temp string.

Finally, all the names arranged in a sorted manner are printed one after another.

Note: If you want to sort the array of strings in reverse-order using a userdefined method then only by reversing the comparison inside the if condition will give us the desired result. The if condition will compare names[j].compareTo(names[i])>0 like this to sort the array in descending order.

Conclusion

The main outcome of this article was to share different ways to sort an array of strings. The ways included both predefined and user-defined methods. I hope you were able to understand the concepts clearly, feel free to ask your queries in the comment section. I will try to resolve all the queries.

Leave a Comment

Your email address will not be published. Required fields are marked *