如何按照从最长到最短的模式用 Java 来对字符串数组进行排序
首先,让我们创建一个字符串数组
String[] strArr = { "ABCD", "AB", "ABCDEFG", "ABC", "A", "ABCDE", "ABCDEF", "ABCDEFGHIJ" }
对于从最长到最短的模式,例如 ABCDEFGHIJ、ABCDEFG、ABCDEF 等等;获取两个字符串数组的长度,并按如下方式对它们进行处理
Arrays.sort(strArr, (str1, str2) → str2.length() - str1.length());
以下是用 Java 将字符串数组按照从最长到最短的模式进行排序的一个示例
示例
import java.util.Arrays; public class Demo { public static void main(String[] args) { String[] strArr = { "ABCD", "AB", "ABCDEFG", "ABC", "A", "ABCDE", "ABCDEF", "ABCDEFGHIJ" }; System.out.println("Sorting array on the basis of their lengths (longest to shortest) = "); Arrays.sort(strArr, (str1, str2) → str2.length() - str1.length()); Arrays.asList(strArr).forEach(System.out::println); } }
输出
Sorting array on the basis of their lengths (longest to shortest) = ABCDEFGHIJ ABCDEFG ABCDEF ABCDE ABCD ABC AB A
广告