如何按照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
以上是 如何按照Java中最长到最短的模式按长度对字符串数组进行排序 的全部内容, 来源链接: utcz.com/z/343467.html