如何按照最短到最长的模式用 Java 对字符串数组进行排序
首先,我们创建一个字符串数组
String[] strArr = { "ABCD", "AB", "ABCDEFG", "ABC", "A", "ABCDE", "ABCDEF", "ABCDEFGHIJ" };
现在,针对最短到最长的模式(例如 A、AB、ABC、ABC 等),获取两个字符串数组的长度并按如下方式操作
Arrays.sort(strArr, (str1, str2) -> str1.length() - str2.length());
以下是一个按照最短到最长的模式对字符串数组排序的示例
示例
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 (shortest to longest) ="); Arrays.sort(strArr, (str1, str2) -> str1.length() - str2.length()); Arrays.asList(strArr).forEach(System.out::println); } }
输出
Sorting array on the basis of their lengths (shortest to longest) = A AB ABC ABCD ABCDE ABCDEF ABCDEFG ABCDEFGHIJ
广告