我正在尝试按特定顺序对数组进行排序。如果 number % 10 等于 0,那么它将首先出现,对于其余的,如果 number mod 10 更大,那么它将首先出现。
Collections.sort(arr,new Comparator<Integer>(){
public int compare(Integer e1, Integer e2) {
if(e1 %10 == 0 && e2 %10 != 0 || (e2 %10 == 0 && e1 %10 != 0)
|| e1 % 10 ==0 || e2 % 10 ==0){
return -1;
}else{
if(e1 % 10 < e2 % 10){
return 1 ;
}else{
return -1 ;
}
}
}});
输入:[120,20,35,7,29]
输出:[29,7,35,20,120]
预期:[120, 20, 29, 7, 35]
最佳答案
返回 0 的比较器表示值相等并且不需要切换。对于您的情况,我们在比较方法中规定,第一个 if 应返回 0。这将为您提供所需的结果。
Collections.sort(arr, new Comparator<Integer>() {
public int compare(Integer e1, Integer e2) {
if (e1 % 10 == 0 && e2 % 10 != 0 || (e2 % 10 == 0 && e1 % 10 != 0) || e1 % 10 == 0 || e2 % 10 == 0) {
return 0;
} else {
if (e1 % 10 < e2 % 10) {
return 1;
} else {
return -1;
}
}
}
});
关于java - 如何使用比较器对数组中的某些特定元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442743/