-1

I have a List containing a variable amount of objects (often more than 1000). These objects have certain attributes, for example price and distance (both int).

Now I want to be able to sort the List from cheapest to most expensive OR from closest to furthest away, but I don't know how to implement this. I already tried making my object implement Comparable, but this only lets me sort by one of the properties... How can I sort based on different properties?

Krease
  • 15,805
  • 8
  • 54
  • 86
SlaterTh90
  • 13
  • 2

2 Answers2

5

Create two different implementations of Comparator - one that compares price, and one that compares distance.

Then you can use Collections.sort(List, Comparator) to sort the list using whichever sorting strategy you want.

Krease
  • 15,805
  • 8
  • 54
  • 86
1

You should just make use the Collections.sort(...) and implement custom comparators for each type of sorting, for example, by price.

Collections.sort(effizientObjects, new Comparator<EffizientObject>() {
    @Override public int compare(EffizientObject p1, EffizientObject p2) {
        return p1.price- p2.price;
    }
});
DominicEU
  • 3,585
  • 2
  • 21
  • 32
  • 3
    NB: you should use [`Integer.compare`](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compare(int,%20int)) (or `Double.compare`, or whichever type) to compare numeric values, rather than subtracting, to avoid overflow. – Andy Turner Jan 29 '16 at 21:22