Sort String Array alphabetically by the initial character only in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 03-May-2019 07:20:48
Advertisements