Avatar of Mutsop
Mutsop
Flag 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.
Java

Avatar of undefined
Last Comment
Mutsop

8/22/2022 - Mon
for_yan

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
for_yan

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
for_yan

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
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
for_yan

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
for_yan

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Mutsop

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