0

I experience some issues about sorting price in Java.

I want from high price to low price and from low to high price respectively in my ArrayList.

ArrayList<orderbook> buyerlist=new ArrayList<orderbook>();

I want buyerlist to sort object sequence by price. I tried below but it does not works.

buyerlist.add(new orderbook(orderrecord.get(i).getSide(),orderrecord.get(i).getVolume(),orderrecord.get(i).getPrice()));
Collections.sort(arraylist);

ArrayList<orderbook> sellerlist=new ArrayList<orderbook>();

I want sellerlist can sort object sequence by price

here is my constructor

public class orderbook {


// here i defined three object of this constructor.
// i want sorting this sequence by price. from high to low and low to high respectively.


    String side;
    int volume;
    double price;

    public orderbook(String side,int volume,double price){
        this.side=side;
        this.volume=volume;
        // compare price is low then 0 will throw exception
        if (volume < 0) {
            throw new IllegalArgumentException("volume size illegal");
        }
        this.price=price;

        if (price < 0) {
            throw new IllegalArgumentException("price > 0 require");
        }
    }


    public String getSide() {
        return side;
    }
    public void setSide(String side) {
        this.side = side;
    }
    public int getVolume() {
        return volume;
    }
    public void setVolume(int volume) {
        this.volume = volume;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }

}
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
user2953788
  • 157
  • 3
  • 17

1 Answers1

0

If you have orderbooks in some Collection for example ArrayList, then you can sort them tis way:

Collections.sort(orderBooks, new Comparator<orderbook> {
    @Override
    public int compare(orderbook ob1, orderbook ob2) {
        return o1.getPrice() - o2.getPrice();
    }
});
Martin Dendis
  • 523
  • 5
  • 9