import java.io.*; import java.util.*; public class wp2 { // To bind the counter during runtime static class ValueHolder { private int count = 1; private final String value; ValueHolder(String tkn) { this.value = tkn; } } public static void main(String[] args) throws IOException { final Map countMap = new HashMap(65535); final StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); st.resetSyntax(); st.wordChars(33, 126); st.whitespaceChars(1, 32); while (st.nextToken() != StreamTokenizer.TT_EOF) { if (st.ttype == StreamTokenizer.TT_WORD) { final String token = st.sval; final ValueHolder count = countMap.get(token); if (count == null) countMap.put(token, new ValueHolder(token)); else count.count++; } } final SortedSet sorted = new TreeSet<>(new Comparator() { @Override public int compare(ValueHolder o1, ValueHolder o2) { // Reverse comparation to get the biggest counts first return o2.count - o1.count; } }); sorted.addAll(countMap.values()); final StringBuilder msg = new StringBuilder(); for (ValueHolder entry : sorted) { msg.append(entry.count).append(" ").append(entry.value).append('\n'); // write here from time to time to System.out in case msg's memory consumption // is unacceptable } System.out.println(msg.toString()); } }