将给定数组中的语义版本排序为字符串 [英] Sort semantic versions in a given array as a string
本文介绍了将给定数组中的语义版本排序为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我输入为:
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};
我被困在找不到比较两个元素的方法的地方.我的代码只比较一次而不是比较所有元素:
I'm stuck where I cant find a way to compare two elements. My code just compare once instead of comparing all the elements:
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;
}
推荐答案
您可以将每个字符串按点分割成一个数组,并按整数值顺序对它们进行排序这些数组的列使用比较器链:
You can split each string into an array by dots and sort them sequentially by the integer values in the columns of these arrays using a chain of comparators:
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"};
String[] b = Arrays
// Stream<String>
.stream(a)
// split a string into an array by dots
// return Stream<String[]>
.map(str -> str.split("\\."))
// sort string arrays by columns: first, second and last
.sorted(Comparator // using a chain of comparators
.<String[]>comparingInt(arr -> Integer.parseInt(arr[0]))
.thenComparingInt(arr -> Integer.parseInt(arr[1]))
.thenComparingInt(arr -> Integer.parseInt(arr[2])))
// join an array of strings back into a single string
// return Stream<String>
.map(arr -> String.join(".", arr))
// return sorted array
.toArray(String[]::new);
// output
System.out.println(Arrays.toString(b));
// [0.0.0, 1.0.0, 1.0.1, 1.1.2, 2.3.4, 12.2.1, 12.2.2, 13.2.4]
另见:如何使用 Map 按字符串中出现的次数对字符进行排序?
这篇关于将给定数组中的语义版本排序为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文