Friday, December 19, 2014

wordCounter Program using HashMap

Look at previous post for the context:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

class wordCounter2 {

String readFile(String fileName) throws IOException {
   BufferedReader br = new BufferedReader(new FileReader(fileName));
   try {
       StringBuilder sb = new StringBuilder();
       String line = br.readLine();

       while (line != null) {
           sb.append(line);
           sb.append(" ");
           line = br.readLine();
       }
       return sb.toString();
   } finally {
       br.close();
   }
}

void countAllWords(String filename) throws IOException
{
String fileContent = readFile(filename);
String[] arr = fileContent.split(" ");

Map<String, Integer> map = new HashMap<>();
   for (String w : arr) 
   {
       Integer n = map.get(w);
       n = (n == null) ? 1 : ++n;
       map.put(w, n);
   }
   
   Map <String, Integer> sortedMap = new TreeMap<String, Integer>(map);
   System.out.println("After Sorting:");
        Set<Entry<String, Integer>> set2 = sortedMap.entrySet();
        Iterator<Entry<String, Integer>> iterator2 = set2.iterator();
        while(iterator2.hasNext()) {
             Map.Entry me2 = (Map.Entry)iterator2.next();
             System.out.print(me2.getKey() + ": ");
             System.out.println(me2.getValue());
        }

        int maxValueInMap=(Collections.max(sortedMap.values()));  // This will return max value in the Hashmap
        for (Entry<String, Integer> entry : sortedMap.entrySet()) {  // Itrate through hashmap
            if (entry.getValue()==maxValueInMap) {
                System.out.println("Max Frequency: " + entry.getKey() + " ==> " + entry.getValue());     // Print the key with max value
            }
        }

}

void countWords(String filename, String word) throws IOException
{

String fileContent = readFile(filename);
String[] arr = fileContent.split(" ");

int counter = 0;

for (int i=0; i<arr.length; i++)
{
if (arr[i].equals(word))
{counter = counter + 1;}
else
continue;
}
System.out.println(counter);
}
}

public class wordCount2{

public static void main (String args[]) throws IOException
{
wordCounter2 wordcounter = new wordCounter2();
wordcounter.countAllWords("hello.txt");
//wordcounter.countWords("hello.txt", "Socket");
}
}

No comments:

Post a Comment