【发布时间】:2018-09-22 05:36:51
【问题描述】:
我有一份员工名单,他们有不同的经历,比如
5.0,3.3,5.5,5.6,4.5 等..
当我尝试使用 Math.round 对最大到最小体验进行排序时,它会给出错误的结果,例如:
5.6,5.0,5.5,5.3,4.5 等..
我想要这样的结果:
5.6,5.5,5.3,5.0,4.5 等..
这里我用Collections.sortlike:
Collections.sort(employeeList, new Comparator<Emp>() {
@Override
public int compare(Emp t, Emp t1) {
return Math.round(t.getExperience() - t1.getExperience()); // which giving wrong results
// return Float.compare(t.getExperience() - t1.getExperience()); // which is not working
}
});
这里t1.getExperience()会给你浮动结果。
【问题讨论】:
-
看到这个答案可能会有所帮助stackoverflow.com/a/3705372/7328984
-
1. Profile 的 Comparator 是比较 Emp1 和 Emp2 类对象 2。没有具体说明什么是体验属性类型。
-
当您比较
Employees 时,Comparator<Profile>会怎样? -
java.lang.Float 已经实现了 Comparable,任何你想这样做的理由。而不是反向比较这两个值?
-
Math.round(t.getExperience() - t1.getExperience())不起作用,因为由于四舍五入,它会认为5.3和5.0相等。这个技巧只适用于整数。
标签: java sorting collections java-8