首页 > 解决方案 > 将数组中给定的语义版本排序为字符串

问题描述

我的输入为:

String[] a = {"1.0.0","13.2.4","1.0.1","0.0.0","2.3.4","1.1.2","12.2.2","12.2.1"};

我希望输出为:

{0.0.0, 1.0.0, 1.0.1, 1.1.2, 2.3.4, 12.2.1, 12.2.2, 13.2.4};

我被困在找不到比较两个元素的方法的地方。我的代码只比较一次,而不是比较所有元素:

public static String[] compare(String[] a) {
    String temp;
    String[] a1;
    String[] a2;

    for (int i = 0; i < a.length - 1; i++) {
        a1 = a[i].split("\\.");
        a2 = a[i + 1].split("\\.");

        for (int j = 0; j < a1.length; j++) {
            int v1 = j < a1.length ? Integer.parseInt(a1[j]) : 0;
            int v2 = j < a2.length ? Integer.parseInt(a2[j]) : 0;

            if (v1 > v2) {
                temp = a[i];
                a[i] = a[i + 1];
                a[i + 1] = temp;
                j = a1.length;
            } else if (v1 == v2) {
                continue;
            } else {
                j = a1.length;
            }
        }
    }
    return a;
}

标签: javaarrayssortingmultidimensional-array

解决方案


这是一种选择。我为演示目的使用了一个夸张的标题列表。你的也应该没问题。

  • 首先,它将级别拆分为字符串数组。
  • 然后它使用这些数组根据节数计算存在的最大级别。
  • 然后它使用级别数来构建足以比较所有级别的比较器。
  • 然后它使用比较器对数组的数组(它们已经拆分)进行排序,并将它们重新加入到原始部分标题中。
String[] sections = { "1.0.0", "13.2.4", "1.0.1", "0.0.0", "2.3.4",
        "1.1.1.1.2.2", "12.2.2.2", "12.2.1" };

// split up the levels into an array of arrays.
String[][] levels =
        Arrays.stream(sections).map(str -> str.split("\\."))
                .toArray(String[][]::new);

// calculate the maximum level
int maxLevel = 0;
for (String[] arr : levels) {
    maxLevel = Math.max(maxLevel, arr.length);
}

// now use that to build the comparator.
Comparator<String[]> comp = Comparator
        .comparingInt(arr -> Integer.parseInt(arr[0]));
for (int i = 1; i < maxLevel; i++) {
    final int k = i;
    comp = comp.thenComparingInt(
            arr -> Integer.parseInt(arr[k]));
}

// and then sort them and rejoin the numbers.
String[] result = Arrays.stream(levels).sorted(comp)
        .map(arr -> Arrays.stream(arr)
                .collect(Collectors.joining(".")))
        .toArray(String[]::new);


Arrays.stream(result).forEach(System.out::println);

印刷

0.0.0
1.0.0
1.0.1
1.1.1.1.2.2
2.3.4
12.2.1
12.2.2.2
13.2.4

推荐阅读