Sorting ArrayList objects using float

I have a stock values ​​archarist, every stock has a name, stock exchange, price and date.

I am trying to organize an arraylist at prices that float.

Any pointers would be appreciated.

+3


source to share


6 answers


Use java.util.Collections.sort()

and specify your own java.util.Comparator

.



+6


source


You need to implement your own Comparator or make your stocprices a Comparable extension



Collections.sort(stockPricesArrayList, new Comparator<StockPrice>() {

    public int compare(StockPrice p1, StockPrices p2) {
         return (int) p1.getPrice()-p2.getPrice();
    }
}

      

+3


source


In your StockPrice class, you can implement Comparable. It will look like this:

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

+1


source


According to the jdk 1.7 requirement, the results should be the same if you change the position of params. So the subtraction will be wrong, I think this is the simplest way to sort floating point arrays:

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

      

+1


source


I am assuming you have a class to store your prices. The easiest way is to implement Comparable in this class and return there like Float.compare(this.price, other.price)

.

0


source


You need to implement the Comparable interface and define a compareTo () method for your class. Once you're done, you can have an arrayist and sort it. See the link for an example. A few more links with importers another example and the difference between comparable and useful comparator information

0


source