package cn.edu.bjut.chapter6; import java.util.Map; import java.util.TreeMap; public class WordCounter { private String[] tokens; private Map counter; public WordCounter(String[] tokens) { this.tokens = tokens; this.counter = new TreeMap(); } public void count() { for (String token : tokens) { if (counter.containsKey(token)) { int count = counter.get(token); counter.put(token, count + 1); } else { counter.put(token, 1); } } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Map.Entry entry : counter.entrySet()) { sb.append(entry.getKey() + ": " + entry.getValue() + "\n"); } return sb.toString(); } }