java - 将数组中给定的语义版本排序为字符串
问题描述
我的输入为:
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;
}
解决方案
这是一种选择。我为演示目的使用了一个夸张的标题列表。你的也应该没问题。
- 首先,它将级别拆分为字符串数组。
- 然后它使用这些数组根据节数计算存在的最大级别。
- 然后它使用级别数来构建足以比较所有级别的比较器。
- 然后它使用比较器对数组的数组(它们已经拆分)进行排序,并将它们重新加入到原始部分标题中。
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
推荐阅读
- javascript - 如果我在一个对象中有一个数组并且该对象在一个大数组中,我该如何更新 React Native 状态?
- protractor - 期望失败时如何将茉莉花配置为注销消息
- python - 如何彻底清除画布
- java - 初始化新的 RecyclerView 适配器是异步调用吗?
- graphql - 带有 Ghost CMS 的 Gatsby.js:如何查询包含当前帖子相同标签的帖子列表
- php - 如何以 php 或任何语言重命名下载文件
- javascript - 在 Three.js 中制作动画时将 3d 模型保持在可见区域内
- python - 重命名树视图和看板视图中的字段 (odoo12)
- c#-4.0 - Interop Excel - 如何将 excel 文件设置为始终在最后一行打开?
- jquery - Jquery 自动滚动到 div + X 像素