How to count associated objects?

I have two objects, which I create from the same class. The class has a public variable named count, so for Object 1 has count = 15, and Object 2 has count = 12. What is the best way to sort such a sequence of objects from least to greatest?

  • Answer:

    In Python, I'd do my_list = [Object1, Object2] sorted_list = sorted(my_list, key=lambda x: x.count) but you are probably not using Python since you mentioned "public variables".

Matt Wartell at Quora Visit the source

Was this solution helpful to you?

Other answers

The idea is to perform transformation before the sorting step, use the result for actual sorting but returning original object in results.   In Python, as has shown, accepts a transform function as argument. In C++ sort [1] / C qsort [2] or Java [3], an "comparator" object can be provided, which defines the result of comparing two given objects. A custom implemented comparator could do such transformations in place before returning the result. [1] http://www.cplusplus.com/reference/algorithm/sort/ [2] http://www.cplusplus.com/reference/cstdlib/qsort/ [3] http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(T%5B%5D,%20java.util.Comparator)

Ryan Gao

For java, implement your class as a http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html and sort it with Collections.sort() or Arrays.sort() or any other means you would like it to be sorted (Put them into a TreeSet, for instance.)

Teng-Pao Yu

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.