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
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
Related Q & A:
- Unix tools: what if a file is named minus something?Best solution by Super User
- What links a click/tap position to select an object on screen?Best solution by Quora
- How do I change HTML content to be a JS variable?Best solution by ehow.com
- Does a 2005 Nissan Altima 2.5SL have a constant variable transmission?Best solution by answers.yahoo.com
- What knot can I use to lash two objects together that will tighten on itself and not release?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.