自制了一个wbsCode层级的JAVA排序算法
1、需要:对“1.1”,“1.2”,“1.3”,“1.1.1”,“2”,“4”,“5”,“4.1.1”,“11” 进行排序
想要的效果:“1.1”,“1.1.1”,“1.2”,“1.3”,“2”,“4”,“4.1.1”,“5”,“11”
如果用JAVA原生的compareTo 比较
public static void main(String[] args) throws Exception {
String[] arr = new String[]{"1.1","1.2","1.3","1.1.1","2","4","5","4.1.1","11"};
List<String> list = Arrays.asList(arr);
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
System.out.println(list); //[1.1, 1.1.1, 1.2, 1.3, 11, 2, 4, 4.1.1, 5]
}
结果不符合预期。11在2的前面显然不对
2、自制一个算法:也很简单。(废弃,偶尔会实效)
1、去除wbsCode里面的小数点,然后再后面补0。转正long类型,进行比较大小。
根据实际实际需求,这里假设,小数点的个数,不会超出9位。
2、在后面补多少个0,要根据wbsCode实际有的小数来判断。补0数 = 9 - wbsCode小数点个数。
public static void main(String[] args) throws Exception {
String[] arr = new String[]{"1.1","1.2","1.3","1.1.1","2","4","5","4.1.1","11"};
List<String> list = Arrays.asList(arr);
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String wbsCode1 = o1.replaceAll("\\.","");
String wbsCode2 = o2.replaceAll("\\.","");
int pointNum1 = 9-o1.split("\\.").length;
int pointNum2 = 9-o2.split("\\.").length;
String zero1 = "";
String zero2 = "";
for(int index=0;index<pointNum1;index++){
zero1 += "0";
}
for(int index=0;index<pointNum2;index++){
zero2 += "0";
}
wbsCode1 = wbsCode1+ zero1;
wbsCode2 = wbsCode2 +zero2;
// 转换为long类型
long wbsCodeLong1 = Long.parseLong(wbsCode1);
long wbsCodeLong2 = Long.parseLong(wbsCode2);
if(wbsCodeLong1 > wbsCodeLong2){
return 1;
}else{
return -1;
}
}
});
System.out.println(list); //[1.1, 1.1.1, 1.2, 1.3, 2, 4, 4.1.1, 5, 11]
}
2、真正可用的。(chartGpt提供的)
public class WBSCodeComparator {
public static int[] parseWBSCode(String code) {
String[] parts = code.split("\\.");
int[] numbers = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
numbers[i] = Integer.parseInt(parts[i]);
}
return numbers;
}
public static int compareWBSCode(String code1, String code2) {
int[] numbers1 = parseWBSCode(code1);
int[] numbers2 = parseWBSCode(code2);
int length1 = numbers1.length;
int length2 = numbers2.length;
int minLength = Math.min(length1, length2);
for (int i = 0; i < minLength; i++) {
if (numbers1[i] < numbers2[i]) {
return -1;
} else if (numbers1[i] > numbers2[i]) {
return 1;
}
}
// If all compared levels are equal, the shorter code is considered smaller
if (length1 < length2) {
return -1;
} else if (length1 > length2) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
String code1 = "1.2";
String code2 = "1.11";
int comparisonResult = compareWBSCode(code1, code2);
if (comparisonResult < 0) {
System.out.println(code1 + " is less than " + code2);
} else if (comparisonResult > 0) {
System.out.println(code1 + " is greater than " + code2);
} else {
System.out.println(code1 + " is equal to " + code2);
}
}
}

浙公网安备 33010602011771号