title: Finding 'n' most frequent words from a file using Java?
body: <p>I want to read an file, and want to collect top <strong>n</strong> words depends on word frequency.</p>
  
  <p>I have tried the following code to count every words in a string. </p>
  
  <pre><code>public static void main(String[] args) throws FileNotFoundException, IOException {
       FileReader fr = new FileReader("txtFile.txt");
       BufferedReader br = new BufferedReader(fr);
       String text = "";
       String sz = null;
       while ((sz = br.readLine()) != null) {
           text = text.concat(sz);
       }
       String[] words = text.split(" ");
       String[] uniqueLabels;
       int count = 0;
       System.out.println(text);
       uniqueLabels = getLabels(words);
  
       for (String l: uniqueLabels) {
           if ("".equals(l) || null == l) {
               break;
           }
           for (String s: words) {
               if (l.equals(s)) {
                   count++;
               }
           }
           System.out.println("Word :: " + l + " Count :: " + count);
           count = 0;
       }
   }
  </code></pre>
  
  <p>And I used the following code to collect unique lbels(<em>words</em>) get if from <a href="https://stackoverflow.com/questions/21771566/calculating-frequency-of-each-word-in-a-sentence-in-java">link</a>,</p>
  
  <pre><code>private static String[] getLabels(String[] keys) {
        String[] uniqueKeys = new String[keys.length];
  
        uniqueKeys[0] = keys[0];
        int uniqueKeyIndex = 1;
        boolean keyAlreadyExists = false;
  
        for (int i = 1; i &lt; keys.length; i++) {
            for (int j = 0; j &lt;= uniqueKeyIndex; j++) {
                if (keys[i].equals(uniqueKeys[j])) {
                    keyAlreadyExists = true;
                }
            }
  
            if (!keyAlreadyExists) {
                uniqueKeys[uniqueKeyIndex] = keys[i];
                uniqueKeyIndex++;
            }
            keyAlreadyExists = false;
        }
        return uniqueKeys;
    }
  </code></pre>
  
  <p>And this works fine, I want to collect top 10 ranked words depend on it's frequency in  file.  </p>