java 按浮点数对对象的 ArrayList 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9941890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting ArrayList of objects by float
提问by Guillaume Polet
I have an arraylist of stockprices each stockprices has a name, stock exchange, price and date.
我有一个股票价格数组列表,每个股票价格都有一个名称、证券交易所、价格和日期。
I am trying to organise the arraylist by prices which are floats.
我正在尝试按浮动价格组织数组列表。
Any pointers would be appreciated.
任何指针将不胜感激。
回答by hmjd
Use java.util.Collections.sort()
and specify your own java.util.Comparator
.
使用java.util.Collections.sort()
并指定您自己的java.util.Comparator
.
回答by troy
According to the require of jdk 1.7, the results must be same when reverse the params's position. So, subtract will be wrong, I think this is the easiest way to sort float arrays:
根据jdk 1.7的要求,颠倒参数的位置时,结果必须相同。所以,减法是错误的,我认为这是对浮点数组进行排序的最简单方法:
Collections.sort(Arrays, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return Float.compare(o1.getFloatValue(), o2.getFloatValue());
}
});
回答by Guillaume Polet
You need to implement your own Comparator or make your stocprices extends Comparable
您需要实现自己的 Comparator 或使您的股票价格扩展 Comparable
Collections.sort(stockPricesArrayList, new Comparator<StockPrice>() {
public int compare(StockPrice p1, StockPrices p2) {
return (int) p1.getPrice()-p2.getPrice();
}
}
回答by Caumons
In your class StockPrice you can implement Comparable. It would look like:
在您的类 StockPrice 中,您可以实现 Comparable。它看起来像:
public class StockPrice implements Comparable<StockPrice> {
// All your code here
@Override
public int compareTo(StockPrice another) {
// price fields should be Float instead of float
return this.price.compareTo(another.price);
}
}
Then you can use Collections.sort()
然后你可以使用 Collections.sort()
回答by Amit
You need to implement the Comparable interface, and define the compareTo() method for your class. Once done you can have an arraylist and sort it. See this linkfor an example. Few more importants links are another exampleand diff between comparable and comparator useful information
您需要实现 Comparable 接口,并为您的类定义 compareTo() 方法。完成后,您可以拥有一个数组列表并对其进行排序。有关示例,请参阅此链接。很少有更重要的链接是 另一个示例以及 可比较和比较器有用信息之间的差异
回答by Neet
I assume you have a class for storing your prices. The easiest way here is to implement Comparablein this class and return someting like Float.compare(this.price, other.price)
.
我假设您有一个用于存储价格的类。这里最简单的方法是在这个类中实现Comparable并返回类似Float.compare(this.price, other.price)
.