仅在Java中按字符串的首字母顺序对字符串数组进行排序

在这里,我们按字母顺序对字符串数组进行排序,即“ John”的“ J”将在“ Chris”之后,因为“ Chris”的第一个字符是“ C”。

让我们首先创建一个String数组:

String[] strArr = { "PQRS", "AB", "RSTUVW", "RST", "U", "UVWXY", "OUJBG" };

现在,根据第一个字符对字符串数组进行排序:

Arrays.sort(strArr, (str1, str2) -> str1.charAt(0) - str2.charAt(0));

下面是一个仅按字母顺序对字符串数组进行字母排序的示例:

示例

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);
   }
}

输出结果

Sorting array strings =
AB
OUJBG
PQRS
RSTUVW
RST
U
UVWXY