如何按照最短到最长的模式用 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

更新于: 30-Jul-2019

709 次查看

开启你的 职业 生涯

通过完成课程获得认证

开始吧
广告