Nice TWiki > Doc > CodeExamples > WordfreqIntermediateExample (r1.2) TWiki webs:
Dev | Doc | Main | TWiki | Sandbox
Doc . { Changes | Index | Search | Go }
/* 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
         }
      );

// Using an external function in a foreach.
   entries.foreach(formatAndPrintLine);
}


class Cell { int value; }


// package function
void formatAndPrintLine(Map.Entry<String,Cell> entry){
   
   let StringBuffer buffer = new StringBuffer(32);
   let sCount = entry.getValue().value.toString();
   var pad = 7 - sCount.length();
   while (pad-- > 0) buffer.append(' ');

   buffer.append(sCount);
   buffer.append("\t");
   buffer.append(entry.getKey());
   println(buffer);
}


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

*/
-- IsaacGouy - 31 Aug 2003

Topic WordfreqIntermediateExample . { Edit | Attach | Ref-By | Printable | Diffs | r1.4 | > | r1.3 | > | r1.2 | More }
Revision r1.2 - 01 Sep 2003 - 12:09 GMT - ArjanB
Parents: WebHome > CodeExamples
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.