import java.util.*;
import java.io.File;
import javax.swing.JFileChooser;

/**
 * jdk1.5 store words and counts
 *
 */

public class WordCount15
{
    public WordCount15()
    {
    	if (ourFileChooser == null){
    		ourFileChooser = new JFileChooser(".");	
    	}
	try{
	    int retval = ourFileChooser.showOpenDialog(null); 
	    if (retval == JFileChooser.APPROVE_OPTION) {
		myFile = ourFileChooser.getSelectedFile();
		myScanner = Scanner.create(myFile);	    
	    }
	}
	catch(Exception e){
	    throw new RuntimeException("file open cancelled in WordReader"); 
	}
    }

    void readAndCount()
    {
	Iterable<String> it = new Iterable<String>(){
		public Iterator<String> iterator(){
		    return myScanner;
		}
	    };
	Map<String,Integer> map = new TreeMap<String,Integer>();
	long start = System.currentTimeMillis();
	for(String w : it) {
	    int count;
	    Integer c = map.get(w);
	    if (c == null){
		map.put(w,1);
	    }
	    else {
		map.put(w,c+1);
	    }
	}
	long end = System.currentTimeMillis();
	for(String w : map.keySet()){
	    System.out.println(map.get(w) + "\t" + w);
	}
	System.out.println("time = "+(end-start)/1000.0);
    }

    public static void main(String[] args){
	WordCount15 wc = new WordCount15();
	wc.readAndCount();
    }
    
    static private JFileChooser ourFileChooser;
    File myFile;
    Scanner myScanner;
}
