0

Let´s say I´ve got a class called Product, with the fields price and weight.

My final objective is to have a list of products that I can sort by price or weight

I know I can make Product implements Comparable<Product>. That means I will have to, for instance:

@Override
public int compareTo(Product compareProduct) {
    int comparePrice = ((Product) compareProduct).getPrice();

    //ascending order
    return this.price - comparePrice;
}

This code will only compare by price, so, in a nutshell, the question is how can I choose the compare method I want to use? (byPrice or byWeight)

stack man
  • 2,303
  • 9
  • 34
  • 54
  • 1
    What does it mean to sort by price or weight? Do you want sort by price, and for equal prices, sort by weight? – Tunaki Sep 11 '16 at 15:12
  • I just want to: A) Get list with all products sorted by price B) Get all products sorted by weight. Is it clear now? Thanks for your attention btw – stack man Sep 11 '16 at 15:14
  • `ow can I choose the compare method I want to use?` Use a custom [Comparator](https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html) – copeg Sep 11 '16 at 15:14
  • Why can't you use `Comparator.comparingInt(Product::getPrice)` and `Comparator.comparingInt(Product::getWeight)`? You need two different comparators in order to compare two different fields. – Tunaki Sep 11 '16 at 15:16
  • @copeg Could you please be more explicit? – stack man Sep 11 '16 at 15:17
  • @Tunaki How can I do that? Please post it as an answer – stack man Sep 11 '16 at 15:18
  • @Tunaki Please read the question again. You marked it as duplicate, but I am not asking how to sort a list, but how to sort it once by one attribute, once by another one – stack man Sep 11 '16 at 15:46
  • I asked you for clarification, and you want to sort it according to one property. Only you want to do it two times for two different properties. The linked answer answers how to do this. You need to invoke it twice. – Tunaki Sep 11 '16 at 15:47
  • @Tunaki Still not agree with you, but anyways... – stack man Sep 11 '16 at 16:27

1 Answers1

3

You could make classes that implement Comparator to use as parameters when running Collections.sort():

static class PriceComparator implements Comparator<Product> {
     public int compare(Product p1, Product p2)
     {
         return p1.getPrice().compareTo(p2.getPrice());
     }
}

static class WeightComparator implements Comparator<Product> {
     public int compare(Product p1, Product p2)
     {
         return p1.getWeight().compareTo(p2.getWeight());
     }
}

And then sort by whichever Comparator you desire:

Collections.sort(productList, new PriceComparator());
...
Collections.sort(productList, new WeightComparator());
Matthew Diana
  • 1,106
  • 7
  • 14