0

I have an array of objects in Java. Let's say Product products[].

Each of those products have a price, for example, product.getPrice().

What's the best way I can order that product array by the price so I can call, products[0] for the most expensive product and products[products.length-1] for the least expensive?

sushain97
  • 2,752
  • 1
  • 25
  • 36
user11406
  • 1,208
  • 1
  • 13
  • 25
  • 1
    Sort `products` by the price of each product via `Arrays.sort()` – vandale Aug 10 '14 at 00:49
  • Define a class that implements `Comparator` and use `Arrays.sort()` or use any sorted collection. – SJuan76 Aug 10 '14 at 00:50
  • What seems to be a problem? – PM 77-1 Aug 10 '14 at 00:50
  • Have `Product` implement `Comparable`. Then you can sort it. – PM 77-1 Aug 10 '14 at 00:54
  • 1
    @SJuan76 could you provide me with an example? I'm not great with Java – user11406 Aug 10 '14 at 00:55
  • 1
    You'll get better at it when you try it by yourself. It is all in the documentation. – SJuan76 Aug 10 '14 at 00:57
  • possible duplicate of [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) or http://stackoverflow.com/questions/18895915/how-to-sort-an-array-of-objects-in-java might be better since you're using an `Array` rather than an `ArrayList` – sushain97 Aug 10 '14 at 01:02
  • why would someone vote to close because its unclear what they're asking. It seems quite clear to me what the question is. – ug_ Aug 10 '14 at 01:16
  • @ug_ yes, it is a "give me the code" question – SJuan76 Aug 10 '14 at 16:20

3 Answers3

4

Something like this:

Arrays.sort(products, new Comparator<Product>() {

    @Override
    public int compare(Product p1, Product p2) {
        if (p1.getPrice() > p2.getPrice()) return -1;
        if (p1.getPrice() < p2.getPrice()) return 1;
        return 0;
    }

});
Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
  • An equivalent way to return: `return p2.getPrice() - p1.getPrice();` for descending, like above. Or, `return p1.getPrice() - p2.getPrice();` for ascending prices. :) – Anonsage Feb 20 '15 at 11:37
1

I would recommend using an ArrayList to do this. Index them in order from most expensive to least expensive using a for loop, like this:

ArrayList products = new ArrayList();
final int MAX_PRICE = 9999; // Or whatever the maximum price should be
for (int i = MAX_PRICE, i > 0, i--) {
    if (product.getPrice() == i) {
        products.add(product);
    }
}
Santiago Benoit
  • 994
  • 1
  • 8
  • 22
0

You can also use Comparable interface to override compareTo method with template T as Products. Then use the following code,

Collections.sort(products);

You can always use Oracle docs for knowing about Comparable Interface at docs.oracle.com

Siddharth Kamaria
  • 2,448
  • 2
  • 17
  • 37