【问题标题】:Java 8 sort float valuesJava 8 排序浮点值
【发布时间】: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&lt;Profile&gt; 会怎样?
  • java.lang.Float 已经实现了 Comparable,任何你想这样做的理由。而不是反向比较这两个值?
  • Math.round(t.getExperience() - t1.getExperience()) 不起作用,因为由于四舍五入,它会认为 5.35.0 相等。这个技巧只适用于整数。

标签: java sorting collections java-8


【解决方案1】:

Math.round(t.getExperience() - t1.getExperience()) 不比较这两个数字,所以我不知道您希望达到什么效果。

你应该使用:

Collections.sort(employeeList, new Comparator<Emp>() {
    @Override
    public int compare(Emp t, Emp t1) {
        return Float.compare(t1.getExperience(), t.getExperience());
    }
});

请注意,传递给Float.compare 的参数与包装compare 方法的参数顺序相反,这将产生按降序 顺序排序。

【讨论】:

  • 也许他想要Comparator.comparing(e -&gt; Math.round(e.getExperience()))
  • @daniu 发布的示例显示常规降序,因此看起来不需要 Math.round()。
  • 当我在上面尝试时,Float 中的比较 (float, float) 不能应用于 (float) @Eran
  • @ShylendraMadda 您没有尝试上述方法。了解一个参数和两个参数之间的区别。
  • @ShylendraMadda -, 不一样
【解决方案2】:

您可以使用Comparator.comparing

 employeeList.sort(Comparator.comparing(Employee::getExperience).reversed());

它会产生:

5.6 5.5 5.0 4.5 3.3

【讨论】:

  • 更好地使用Comparator.comparingDouble。避免不必要的拳击。
猜你喜欢
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
相关资源
最近更新 更多