Search code examples
javasortingcomparable

Java: Effizient List Sorting


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?


Solution

  • 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;
        }
    });