Link to home
Start Free TrialLog in
Avatar of Mutsop
MutsopFlag for Belgium

asked on

java sorting list using data from key/value

Hi,

I'm kinda in struggle here.
So I have a class Word which would just return Strings (but needed it for the equals method to equalsIgnoreCase())
I also have a WordScores class which containc a key/value collections of Words and scores (scores being the score of how much the word is being used)

Now in the WordScores class I have a method: sortByScore(java.util.List<Word> words)

the meaning would be to sort the list words by scores of the key/value collection. Also when the score is the same it should be sorted alphabetically.

Now I'm not sure what collection type to use for the key/value pair...
Also I hoped Collections.sort(words) would work to first sort it alphabetically but doesn't work as it doesn't know its a collection of objects containing only Strings.
Avatar of for_yan
for_yan
Flag of United States of America image

You can use TreeMap, that will have your m,ap soprted buy the natural order of the keys:


http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html
So you can indeed suse TreeMap with word as key and score as value then it will keep them sorted all the time

Alternatively you should make sure the your class Word implemantes Comaprable interface or uyou can use method
Collections.sort(words, Comapartoer) to soerrt them
In fact I think the best choice for you is to use metod

Collections.sort(words, Comparator) and depemdning on which comparaotr you use it will sort either by words or by the score with all the details inside - the way you'll define the method in your Comparator
look at this linke to see an example how to use Comparoator:

http://www.vogella.de/blog/2009/08/04/collections-sort-java/
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mutsop

ASKER

Wasn't suspecting so many answers from one use :)
thanks