Write a java program to sort array or list of string in alphabetical order.
Sometimes we are asked to sort strings or names array into dictionary or lexicographical order, that also means Alphabetical order so don’t get confused.
Example:
1 2 | Input: ["Python", "Java", "C", "JavaScript", "C++"] Output: ["C", "C++", "Java", "JavaScript", "Python"] |
So we need to compare two strings alphabetically i.e character by character. For that, we will use the String class compareTo() method.
compareTo() in Java
compareTo() is a String class method which returns the lexicographical difference between two Strings(i.e compares two strings lexicographically). compareTo() method can be accessed by the instance of String class.
Example:
1 2 3 4 5 6 7 8 9 10 11 | String str1 = "A", str2 = "B"; str1.compareTo(str2); // returns -1 String str1 = "C", str2 = "B"; str1.compareTo(str2); // returns -1 String str1 = "ad", str2 = "ab"; str1.compareTo(str2); // returns 2 String str1 = "A", str2 = "a"; str1.compareTo(str2); // returns 2 |
So if the compareTo() returns +ve number then first string (i.e str1) should come after second string (i.e str2) in the dictionary, else vice-versa.
Since the compareTo() method treats the upper case alphabet (e.g A) and lower case (e.g a) alphabet differently, so we first need to transform the strings into the lower case using String class toLowerCase() method before comparing them.
We will use Bubble Sort algorithm in this program.
Sort String Array in Java using compareTo()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class Main { public static void main(String[] args) { String names[] = {"Python", "Java", "C", "JavaScript", "C++"}; String temp; for(int i=0; i<names.length-1; i++){ for(int j=0; j<names.length-1-i; j++){ String str1 = names[j].toLowerCase(); String str2 = names[j+1].toLowerCase(); //If difference is +ve then swap if(str1.compareTo(str2)>0){ temp = names[j]; names[j] = names[j+1]; names[j+1] = temp; } } } //Output the sorted array for(int i=0; i<names.length; i++){ System.out.print(names[i]+" "); } } } |
Output
1 | C C++ Java JavaScript Python |
Sort String List in Java
Though we can use the same mechanism i.e using compareTo() method, as done in the above program to sort a String list but there is another simple way to sort List in Java by using Collections.sort() available in java.util package.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.util.Arrays; import java.util.List; import java.util.Collections; class Main { public static void main(String[] args) { //Creating List with predefined strings List<String> nameList = Arrays.asList("Python", "Java", "C", "JavaScript", "C++"); //sorting the list Collections.sort(nameList); //output the sorted list for(String name: nameList){ System.out.print(name+" "); } } } |
Output
1 | C C++ Java JavaScript Python |
If you have any doubts or suggestion then comment below.