Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Sort String Array alphabetically by the initial character only in Java
Here, we are sorting string array alphabetically by the initial character i.e. ‘J’ for ‘John’ will come after ‘Chris’ since the first character of ‘Chris’ is ‘C’.
Let us first create a String array:
String[] strArr = { "PQRS", "AB", "RSTUVW", "RST", "U", "UVWXY", "OUJBG" };
Now, sort the string array based on the first character:
Arrays.sort(strArr, (str1, str2) -> str1.charAt(0) - str2.charAt(0));
The following is an example to sort String Array alphabetically by the initial character only:
Example
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
String[] strArr = { "PQRS", "AB", "RSTUVW", "RST", "U", "UVWXY", "OUJBG" };
System.out.println("Sorting array strings = ");
Arrays.sort(strArr, (str1, str2) -> str1.charAt(0) - str2.charAt(0));
Arrays.asList(strArr).forEach(System.out::println);
}
}
Output
Sorting array strings = AB OUJBG PQRS RSTUVW RST U UVWXY
Advertisements
