有时候需要对安卓版本号排序,在此记录一下。
话不多说,先上代码:
public static void main(String[] args) {
long begin = System.currentTimeMillis();
List<String> list = new ArrayList<>();
list.add("Android7");
list.add("Android2");
list.add("Android2.1");
list.add("Android4");
list.add("Android3");
list.add("Android5");
list.add("Android6");
list.add("Android6.1");
list.add("Android6.2");
list.add("Android10");
list.add("Android10.1");
list.add("Android11.2");
list.add("Android3.1.2");
list.add("Android7.2.3");
list.add("Android3.2");
Collections.sort(list, (o1, o2) -> {
int[] var1 = getVersionArray(o1.substring(7));
int[] var2 = getVersionArray(o2.substring(7));
int lim = Math.min(var1.length, var2.length);
int k = 0;
while (k < lim) {
if (var1[k] == var2[k]) {
k++;
continue;
}
return var1[k] - var2[k];
}
if (var1.length == var2.length) {
return 0;
}
return var1.length - var2.length;
});
list.forEach(System.out::println);
long end = System.currentTimeMillis();
System.out.println("排序耗时:" + (end - begin) + "ms");
}
public static int[] getVersionArray(String version) {
String[] array = version.split("\\.");
int[] varray = new int[array.length];
int k = 0;
while (k < array.length) {
varray[k] = Integer.parseInt(array[k]);
k++;
}
return varray;
}
这是一开始的代码,但并不适用于包含比如Android8.a 、Android8.c,带有字符串的版本号。改进一下,适用所有版本号的排序:
public static void main(String[] args) {
long begin = System.currentTimeMillis();
List<String> list = new ArrayList<>();
list.add("Android7");
list.add("Android2");
list.add("Android2.1");
list.add("Android4");
list.add("Android3");
list.add("Android5");
list.add("Android6");
list.add("Android6.1");
list.add("Android6.2");
list.add("Android10");
list.add("Android10.1");
list.add("Android11.2");
list.add("Android3.1.2");
list.add("Android7.2.3");
list.add("Android3.2");
list.add("Android8.a");
list.add("Android8.c");
list.add("Android1.2.a");
Collections.sort(list, (o1, o2) -> {
String version1 = o1.substring(7);
String version2 = o2.substring(7);
return compareVersion(version1, version2);
});
list.forEach(System.out::println);
long end = System.currentTimeMillis();
System.out.println("排序耗时:" + (end - begin) + "ms");
}
public static int compareVersion(String version1, String version2) {
String[] version1Array = version1.split("\\.");
String[] version2Array = version2.split("\\.");
int lim = Math.min(version1Array.length, version2Array.length);
int index;
int diff = 0;
for (index = 0; index < lim; index++) {
//先比较字符长度,比如6,10
diff = version1Array[index].length() - version2Array[index].length();
if (diff != 0) {
break;
}
//长度一样,再比较字符
diff = version1Array[index].compareTo(version2Array[index]);
if (diff != 0) {
break;
}
}
//此时若还未区分出大小,则比较版本号的长度,看是否有子版本
diff = (diff != 0) ? diff : version1Array.length - version2Array.length;
return diff;
}
最终排序结果如下,最终是我们想要的效果: