MayoMan
MayoMan

Reputation: 4917

Most efficient way to Sort a large list of Objects

I have the following simple class, containing a String and an Int.

private static class SuggestionAndScore
{
    private String suggestion; 
    private int score;  
}

I will have a List of these objects which may contain up on 500,000 items. What is the best way to sort this based on the value of score? Should I have the class implement Comparator and use Collections.sort on it or it there a better way? Performance is critical so hence my question as I want to make sure I get the best solution.

Upvotes: 1

Views: 3789

Answers (2)

arya
arya

Reputation: 170

One needs to understand that the sorting methods loads the entire collection into memory, so in case your SuggestionAndScore object is big (probably because of the big suggestion string), you will consume huge amount of memory and could potentially even crash the system. If you believe memory could be a concern then use in-place sorting. If memory isnt a problem then use TreeSet.

Upvotes: 1

PC.
PC.

Reputation: 7024

If all your objects are unique then use TreeSet. Gives the best performance since the objects are already stored in sorted order. (You need not even call Collections.sort())

Upvotes: 0

Related Questions