Introduction
In this post, we will learn the following two examples
a) Sort single String in alphabetical order
b) Sort array of Strings
Sort single String in alphabetical order
import java.util.Arrays;
public class SortStringAlphabetical {
private static String inputString = "The quick brown fox jumps over the lazy dog";
public static void main(String[] args) {
System.out.println("Input String : " + inputString);
char [] characters = inputString.toCharArray();
Arrays.sort(characters);
System.out.println("Alphabetical sorted String : " + new String(characters));
}
}
Output
Input String : The quick brown fox jumps over the lazy dogAlphabetical sorted String : Tabcdeeefghhijklmnoooopqrrstuuvwxyz
Sort array of Strings
import java.util.Arrays;
public class SortStringArrayAlphabetical {
private static String inputStrings[] = {"efg","xyz","abc"};
public static void main(String[] args) {
System.out.println("Input Strings : ");
Arrays.stream(inputStrings).forEach(System.out::println);
System.out.println("Sorted Array : ");
Arrays.sort(inputStrings);
Arrays.stream(inputStrings).forEach(System.out::println);
}
}
Output
Input Strings :
efg
xyz
abc
Sorted Array :
abc
efg
xyz
Conclusion
In this tutorial, we learned how to sort a single string and array of strings in alphabetical order using Java language. Happy learning :)
Comments
Post a Comment