Pages

Getting unique words and word frequencies for a give array in JAVA


package com.esc.xyz;

/**
 * This class provide basic utility function for word.
 * 
 * @author xyz
 * @version 1.0.0
 */

import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;


public class WordUtil {

    /**
     * return the size of array
     * 
     * @param words
     * @return int
     * 
     * 
     */
    
    public int getSize(String[] words) {
        int size = words.length;

        return size;
    }

    /**
     * Provides unique word in a string
     * 
     * @param words
     * @return Set
     */
    
    public Set<String> getUniqueWords(String[] words) {

        Set<String> uniqueWords = new HashSet<String>();
        for (String word : words) {
            uniqueWords.add(word.toLowerCase());
        }

        System.out.println(uniqueWords);
        return uniqueWords;
    }

    /**
     * Provide the word frequencie of the words given in string
     * 
     * @param words
     * @return Map
     */
    public Map<String, Integer> getFreuency(String[] words) {

        Map<String, Integer> wordsFrequencies = new HashMap<>();

        for (String word : words) {
            
            Integer index = wordsFrequencies.get(word.toLowerCase());

            wordsFrequencies.put(word.toLowerCase(), (index == null) ? 1 : index + 1);

        }

        System.out.println(wordsFrequencies);
        return wordsFrequencies;
    }

    public static void main(String[] args) {

        String[] words = { "Ram", "is", "a", "Ram", "good", "boy", "boy",
                "girl", "girl","ram","the","at","at","on"};
        WordUtil wordFrequency = new WordUtil();
        wordFrequency.getUniqueWords(words);
        wordFrequency.getFreuency(words);
    }

}

No comments:

Post a Comment