# Sort by Word frequency and alphabetically

• 01-06-2011, 06:23 PM
darpan12
Sort by Word frequency and alphabetically
hi there i need quick help.

I have got this code:
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}
• 01-06-2011, 07:15 PM
user0
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,
• 01-06-2011, 07:24 PM
Fubarable
Moderator edit: code tags added to original post
• 01-06-2011, 07:26 PM
Fubarable
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.