Friday 30 November 2012

Word Frequency Count :: Java

Word Frequency Count
This program prints the words in order of their frequencies. Higher frequency word will appear on top and words with same frequency will be sorted alphabetically.

import java.util.HashMap;
import java.util.Arrays;

public class WordFrequencyCounter{
   
    private class Word implements Comparable<Word>{
        String word;
        int count;
        public Word(String word, int count){
            this.word=word;
            this.count=count;
        }
        public int compareTo(Word otherWord){
            if(this.count == otherWord.count){
                return this.word.compareTo(otherWord.word);
            }
            return (otherWord.count - this.count);
        }
    }
   
    private Word[] getFrequentWords(String words[]){
        HashMap<String, Word> map = new HashMap<String, Word>();
        for(String s:words){
            Word w = map.get(s);
            if(w == null){
                w = new Word(s, 1);
            }else{
                w.count++;
            }
            map.put(s, w);
        }
        Word[] list = map.values().toArray(new Word[]{});
        Arrays.sort(list);
        return list;
    }
   
    public static void main(String... args){
        String[] words = {"hello", "hi", "how", "are", "you", "what's up", "hi", "hello"};
        Word[] frequency = new WordFrequencyCounter().getFrequentWords(words);
        for(Word w:frequency){
            System.out.println(w.word+" "+w.count);
        }
    }
} 


profile for Mohammad Faisal at Stack Overflow, Q&A for professional and enthusiast programmers