帮助使用比较器比较浮点成员变量
我可以很好地比较字符串,但想知道如何对浮点数进行排名?
getChange() 返回一个字符串。我希望能够按降序排序。我该怎么做?
更新:
package org.stocktwits.helper;
import java.util.Comparator;
import org.stocktwits.model.Quote;
public class ChangeComparator implements Comparator<Quote>
{
public int compare(Quote o1, Quote o2) {
float change1 = Float.valueOf(o1.getChange());
float change2 = Float.valueOf(o2.getChange());
if (change1 < change2) return -1;
if (change1 == change2) return 0; // Fails on NaN however, not sure what you want
if (change2 > change2) return 1;
}
}
我收到编译时错误:
This method must return a result of type int ChangeComparator.java
I am able to compare Strings fine, but would like to know how I can rank floating point numbers?
getChange() returns a String. I want to be able to sort descending. How can I do this?
UPDATE:
package org.stocktwits.helper;
import java.util.Comparator;
import org.stocktwits.model.Quote;
public class ChangeComparator implements Comparator<Quote>
{
public int compare(Quote o1, Quote o2) {
float change1 = Float.valueOf(o1.getChange());
float change2 = Float.valueOf(o2.getChange());
if (change1 < change2) return -1;
if (change1 == change2) return 0; // Fails on NaN however, not sure what you want
if (change2 > change2) return 1;
}
}
I am getting the compile time error:
This method must return a result of type int ChangeComparator.java
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
阅读 的 javadoc
Comparator#compare()
方法。所以,基本上:
或者如果您喜欢条件运算符:
但是,您需要考虑
Float.NaN
。我不确定您希望如何订购它们。第一的?最后的?平等吗?Read the javadoc of
Comparator#compare()
method.So, basically:
Or if you like conditional operators:
You however need to take account with
Float.NaN
. I am not sure how you'd like to have them ordered. First? Last? Equally?怎么样:
请注意,Java 1.4 引入了
Float#compare(float, float)
(以及Double
中的等效项),几乎可以直接使用:(编辑后,我请注意@BorislavGizdov 已经在他的回答中提到了这一点。)
还值得注意的是 Java 8
Comparator#comparing(...)
和Comparator#comparingDouble(...)
提供了一种直接构建这些比较器的简单方法。将使用盒装
Float
值进行比较。将使用提升为
double
值的float
值进行比较。鉴于没有
Comparator#comparingFloat(...)
,我的首选是使用comparingDouble(...)
方法,因为这仅涉及原始类型转换,而不是拳击。How about this:
Note that Java 1.4 introduced
Float#compare(float, float)
(and an equivalent inDouble
), which can be pretty much used directly:(After editing, I notice that @BorislavGizdov has mentioned this in his answer already.)
Also worth noting that Java 8
Comparator#comparing(...)
andComparator#comparingDouble(...)
provide a straightforward way of constructing these comparators directly.Will compare using boxed
Float
values.Will compare using
float
values promoted todouble
values.Given that there is no
Comparator#comparingFloat(...)
, my preference would be to use thecomparingDouble(...)
method, as this only involves primitive type conversion, rather than boxing.您可以使用
Float.compare(float f1, float f2)
:You can use
Float.compare(float f1, float f2)
: