Win a copy of The Java Performance Companion this week in the Performance forum!

# I need a special sort algorithm

M Burke
Ranch Hand
Posts: 406
Hi, wonder of someone has the insight to give me a method that can sort and return a list of RefinedWord objects (See code below):

Output the top 20 by the Integer value ( freqOfWord) sorted in descending order
But here is the trick: Include objects with equal freqOfWord values. So it is possible to return more than 20 objects if there are duplicates.

1. Input is an ArrayList of RefinedWord objects
2. - and + integer values are valid for freqOfWord
3. Duplicate Integers are valid for freqOfWord
4. String values for wordValue are unique
5. The value of wordValue are already unique in the input list, so no test needs to be made for this.

Here is the object to sort

Joanne Neal
Rancher
Posts: 3742
16
1. Sort the ArrayList using a comparator based on the word frequency
2. Get the first element from the sorted list
4. Continously add elements from original list to output list whilst the word frequency is the same
5. Get the next element from the sorted list.
Repeat steps 3 to 5 for however many frequencies you need

M Burke
Ranch Hand
Posts: 406
Yes, that works great, thanks

Here is my code, btw...

Joanne Neal
Rancher
Posts: 3742
16
Lines 25 - 32 of your compare method could be simplified to

Winston Gutkowski
Bartender
Posts: 10427
63
M Burke wrote:Here is my code, btw...

Well done.

A couple of points however:
1. You don't need all that logic to make RefinedWordComparator a singleton. In fact, SingletonsAreEvil.
Just make it a regular class and create instances with new.

2. You could possibly do things with a bit less code if, instead of using a List, you used a HashMap of words and their counts (and AtomicInteger makes a very good 'counter' class). Not that there's anything wrong with how you're doing it now; just letting you know that there are usually lots of ways of doing things.

Winston