I am looking for a data structure that will sort objects based on a given integer. Like so:
Object Score
Object1 86
Object2 85
Object3 85
Each object will be unique, but there can be duplicate scores. Was trying to devise a way on how a Map object could do this, but can’t figure it out.
Structure can either sort the objects during/after an insertion or when I implicitly call for a sort.
Is there a structure out there that does this already? Or should I code it myself?
Try putting the objects in a
SortedSetif you want unique values or aListif you want to see duplicates, along with a customComparatorto sort them based on their “scores”.Providing your own Comparator will let you specify that the objects should be sorted on their
scorefield and how.The Comparator is also reusable and easy to swap in / out if you wanted to, say do a descending sort on the items.
So an example that might be:
And here’s the output of the above code: