# Thread: Sort by Word frequency and alphabetically

1. Member
Join Date
Jan 2011
Posts
1
Rep Power
0

## Sort by Word frequency and alphabetically

hi there i need quick help.

I have got this code:
Java Code:
```[B]public String countAndSort(Vector<String> a){

for (int i=0; i<a.size();i++) {

Integer freq = m.get(a.elementAt(i));
m.put(a.elementAt(i), (freq == null) ? 1 : freq + 1);
}

// System.out.println(m.size() + " distinct words:");
ArrayList<Map.Entry<String, Integer>> word = new ArrayList<Map.Entry<String, Integer>>(m.entrySet());
Collections.sort(word, [COLOR="Red"]new Comparator<Map.Entry<String, Integer>>()[/COLOR]);

[COLOR="Red"]RED = doesn't work;[/COLOR]

System.out.println(m);

return "";
}
}
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
int c1 = o1.getValue().intValue();
int c2 = o2.getValue().intValue();
if (c1 < c2) {
return -1;

} else if (c1 > c2) {
return 1;

} else { // If counts are equal, compare keys alphabetically.
return o1.getKey().compareTo(o2.getKey());
}
}

[/B]```
This doesn't sort by word frequency or alphabetically. :/ Also i want to write the code with arrow in different way if possible.

Example:

Say that vector has "It was the best of times, it was the worst of times," then it prints out {of=2, it=2, times=2, worst=1, best=1, the=2, was=2}
Last edited by Fubarable; 01-06-2011 at 07:23 PM. Reason: Moderator Edit: code tags added

2. Senior Member
Join Date
Dec 2010
Posts
100
Rep Power
0
Hi - can you please use the code tags and post your code in more readable format. With its current format its difficult to read/understand.

Best,

3. OP, get rid of the comments that aren't part of your real code and let's see your real code. What you've posted doesn't look like it is valid syntax for an anonymous inner class, but it's verry difficult to tell with the extra stuff you've added to your post. Also, I agree, please use code tags (see the link in my signature below). If your code doesn't compile, then post your exact error messages and indicate with a valid Java comment where the error occurs. Same for run-time exceptions.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•