Nice TWiki > Doc > CodeExamples > WordfreqIntermediateExample (r1.1) 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){
   var String word;
   let buffer = new StringBuffer(32);
   let HashMap<String,Cell> wordCounts = new HashMap();


// local function
   void flushWordBuffer(){
      ?Cell count;
      if (buffer.length() > 0) { 
         word = notNull( buffer.toString() );
         if ((count = wordCounts.get(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, newCount; 
      char c;
      while ((v = r.read()) != -1) {
         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) => {
         int i = e2.getValue().value - e1.getValue().value;    // sort by frequency
         if (i == 0) i = e2.getKey().compareTo( e1.getKey() ); // sort by word
         return i;
         }
      );


   Iterator<Map.Entry<String, Cell>> item = entries.iterator();
      while(item.hasNext()) {
         Map.Entry<String, Cell> e = item.next();
         println( formatLine(word: e.getKey(), count: e.getValue()) );
      }
}


class Cell { int value; }


// package variable and function

let StringBuffer buffer = new StringBuffer(32);

String formatLine(String word, Cell count){
   buffer.setLength(0);
   String sCount = Integer.toString(count.value);
   int pad = 7 - sCount.length();

   while (pad-- > 0) buffer.append(' ');

   buffer.append(sCount);
   buffer.append("\t");
   buffer.append(word);
   return buffer.toString();
}


/* 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.1 - 31 Aug 2003 - 23:14 GMT - IsaacGouy
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.