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

java 8object oriented programmingprogramming更新于 2025/9/1 14:36:17

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

首先创建一个字符串数组:

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

相关文章