TWiki . Doc . WordfreqIntermediateExample

/* Please try the BeginnerExamples before the IntermediateExamples
To compile:
   nicec --sourcepath=.. -a wordfreq.jar wordfreq
To run:
   java -jar wordfreq.jar < input.txt
*/

import java.io.*;


void main(String[] args){
   let buffer = new StringBuffer(32);
   let HashMap<String,Cell> wordCounts = new HashMap();


// local function
   void flushWordBuffer(){
      ?Cell count;
      if (buffer.length() > 0) { 
         var word = buffer.toString();
         if ((count = wordCounts[word]) == null) 
            wordCounts.put(word, new Cell(value: 1));
         else 
            count.value++;
         buffer.setLength(0);
      }
   }


   try 
   {
      let r = new BufferedReader(new InputStreamReader(System.in));
      int v; 
      while ((v = r.read()) != -1) {
         let c = char(v);
         if (Character.isLetter(c)) 
            buffer.append(Character.toLowerCase(c));
         else 
            flushWordBuffer();
      }
      flushWordBuffer();
   } 
   catch (IOException e) { 
      System.err.println(e); }

   ArrayList<Map.Entry<String, Cell>> entries = new ArrayList(wordCounts.entrySet());

// Use an anonymous function to define the sort, no type casts needed
   sort( entries, 
      (Map.Entry<String, Cell> e1, Map.Entry<String, Cell> e2) => {
         let i = e2.getValue().value - e1.getValue().value; // sort by frequency
         if (i != 0) return i;
         else return e2.getKey().compareTo( e1.getKey() );  // sort by word
         }
      );

   for (each : entries) {
      buffer.setLength(0);
      let count = each.getValue().value.toString();
      var pad = 7 - count.length();
      while (pad-- > 0) buffer.append(' ');

      buffer.append(count);
      buffer.append("\t");
      buffer.append(each.getKey());
      println(buffer);
   }
}


class Cell { int value; }


/* Notes - language
Compare with Java at the "Win32 Language Shootout"
http://dada.perl.it/shootout/wordfreq.html

*/
-- IsaacGouy - 31 Aug 2003

----- Revision r1.4 - 02 Sep 2003 - 01:49 GMT - IsaacGouy
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.