简体   繁体   中英

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

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

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

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

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 link for an example. Few more importants links are another example and diff between comparable and comparator useful information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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