import java.io.File;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

public class TreeMapEntryExample {
    
    public TreeMapEntryExample() {
        Map<String,Integer> wordFrequencies = new TreeMap<String,Integer>();
        try {
            Scanner in = new Scanner(new File("src/TreeMapEntryExample.java"));
            in.useDelimiter("[^a-zA-Z]+");
            while( in.hasNext() ) {
                String aWord = in.next();
                if( !wordFrequencies.containsKey(aWord) ) {
                    wordFrequencies.put(aWord,0);
                } // end if
                wordFrequencies.put(aWord,wordFrequencies.get(aWord)+1);
            } // end while
        } catch(Exception e) {
            JOptionPane.showMessageDialog(null,e);
            e.printStackTrace();
        } // end try/catch
        String out = "";
        for(Map.Entry<String,Integer> entry : wordFrequencies.entrySet() ) {
            String aWord = entry.getKey();
            int frequency = entry.getValue();
            out += aWord + " appeared " + frequency + " time" + (frequency>1?"s":"") + ".\n";
        } // end while
        JTextArea outArea = new JTextArea(40,40);
        outArea.setText(out);
        JOptionPane.showMessageDialog(null,new JScrollPane(outArea));
        Set<Map.Entry<String,Integer>> frequencyWords =  new TreeSet<Map.Entry<String,Integer>>(new CompareWordsByFrequency());
        frequencyWords.addAll(wordFrequencies.entrySet());
        out = "";
        for(Map.Entry<String,Integer> entry : frequencyWords ) {
            String aWord = entry.getKey();
            int frequency = entry.getValue();
            out += aWord + " appeared " + frequency + " time" + (frequency>1?"s":"") + ".\n";
        } // end while
        outArea.setText(out);
        JOptionPane.showMessageDialog(null,new JScrollPane(outArea));
    } // end constructor
    
    class CompareWordsByFrequency implements Comparator<Map.Entry<String,Integer>> {
        public int compare(Map.Entry<String,Integer> left, Map.Entry<String,Integer> right) {
            int leftFreq = left.getValue();
            int rightFreq = right.getValue();
            if( leftFreq != rightFreq ) {
                return rightFreq - leftFreq;
            } else {
                return left.getKey().compareTo(right.getKey());
            } // end else
        } // end compare
    } // end CompareWordsByFrequency
    
    public static void main(String[] args) {
        new TreeMapEntryExample();
        System.exit(0);
    } // end main
    
} // end TreeMapExample


