This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Java in General and the fly likes I need a special sort algorithm Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Java in General
Bookmark "I need a special sort algorithm" Watch "I need a special sort algorithm" New topic

I need a special sort algorithm

M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 395
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

Joined: Aug 05, 2005
Posts: 3742
1. Sort the ArrayList using a comparator based on the word frequency
2. Get the first element from the sorted list
3. Add the element into your output 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

Joined: Jun 25, 2004
Posts: 395
Yes, that works great, thanks

Here is my code, btw...

Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
Lines 25 - 32 of your compare method could be simplified to
Winston Gutkowski

Joined: Mar 17, 2011
Posts: 8661

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.


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: I need a special sort algorithm
It's not a secret anymore!