简体   繁体   English

按浮点数对对象的 ArrayList 进行排序

[英]Sorting ArrayList of objects by float

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.任何指针将不胜感激。

According to the requirements of JDK 1.7, the results must be the same when reversing the params' position根据JDK 1.7的要求,颠倒params的位置时结果必须相同

comparator.compare(a, b) == -comparator.compare(b, a)

So, subtract will be wrong, I think the below code is the easiest way to sort float arrays所以,减法会出错,我认为下面的代码是对浮点数组进行排序的最简单方法

Collections.sort(Arrays, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return Float.compare(o1.getFloatValue(), o2.getFloatValue());
            }
        });

使用java.util.Collections.sort()并指定您自己的java.util.Comparator

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();
    }
}

In your class StockPrice you can implement Comparable.在您的类 StockPrice 中,您可以实现 Comparable。 It would look like:它看起来像:

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()

I assume you have a class for storing your prices.我假设您有一个用于存储价格的类。 The easiest way here is to implement Comparable in this class and return someting like Float.compare(this.price, other.price) .这里最简单的方法是在这个类中实现Comparable并返回类似Float.compare(this.price, other.price)

You need to implement the Comparable interface, and define the compareTo() method for your class.您需要实现 Comparable 接口,并为您的类定义 compareTo() 方法。 Once done you can have an arraylist and sort it.完成后,您可以拥有一个数组列表并对其进行排序。 See this link for an example.有关示例,请参阅此链接 Few more importants links are another example and diff between comparable and comparator useful information很少有更重要的链接是另一个示例以及可比较和比较器有用信息之间的差异

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM