如何按照Java中最短到最长的模式按长度对字符串数组进行排序
首先,让我们创建字符串数组:
String[] strArr = { "ABCD", "AB", "ABCDEFG", "ABC", "A", "ABCDE", "ABCDEF", "ABCDEFGHIJ" };
现在,从最短到最长的模式,例如A,AB,ABC,ABCD等;获得两个字符串数组的长度,并像这样工作:
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
以上是 如何按照Java中最短到最长的模式按长度对字符串数组进行排序 的全部内容, 来源链接: utcz.com/z/327257.html