I have an array which i need to sort its elements by occurrence then alphabetically.
For example:
55 The
32 ASomething
32 BSomething
ASomething should come before Bsomething because:
1) they have the same number
2) A comes before B alphabetically
So you sort first by the number of occurrence then Alphabetically
What is the best way to do that.
I am using merge sort to sort the counts but how do I put a statement that it will check if they have the same number, it sorts alphabetically (could be more than 2 words).
SOLUTION: What I did is a merge sort on the data before I did a merge sorts on the counts of data and that was good enough 🙂 Thanks everyone for the help
You need a custom
Comparatorfor that usingArrays.sort():For
Collectionsyou can useCollections.sort()The above assumes your array elements are
Strings like"22 ASomething"rather than a specific data structure containing occurrences and some text. If that is the case you can use a simplerComparator.Also if you do have an array of
Strings it might be worth first transforming it into an array of objects that have been parsed to save over-parsing the elements (ie some elements will be parsed more than once).