import java.util.*;
public class IntegerComparator implements Comparator {
@Override
public int compare(Integer num1, Integer num2) {
// 计算数字5的数量
int count1 = countFive(num1);
int count2 = countFive(num2);
// 比较数字5的数量,如果相同则比较原数值大小
if (count1 == count2) {
return num1.compareTo(num2);
} else {
return Integer.compare(count1, count2);
}
}
// 计算数字5的数量
private int countFive(int n) {
int count = 0;
while (n > 0) {
if (n % 10 == 5) {
count++;
}
n /= 10;
}
return count;
}
}
在排序时使用该比较器:
List list = Arrays.asList(35, 50, 555, 22, 15, 55555);
Collections.sort(list, new IntegerComparator());
System.out.println(list); // [22, 15, 50, 35, 555, 55555]
这样就可以按照数字5的数量来排序整数列表了。