+import java.io.File;
+import java.util.Scanner;
+import java.io.IOException;
+import java.util.TreeMap;
+import java.util.SortedMap;
class Main {
* @param String[] args main() function arguments array
*/
public static void main(String[] args) {
+ //TreeMap<String, Integer> tm = new TreeMap<String, Integer>(new StrComparator());
+ // default TreeMap comparator keep alphabetical order
+ TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
+ File f = new File("test_file.txt");
+ try {
+ Scanner sc = new Scanner(f);
+ while (sc.hasNext()) {
+ String wordCursor = sc.next();
+ //NOTE: words comparaison is case sensitive and punctuation aware
+ Integer count = tm.get(wordCursor);
+ if (count == null) {
+ count = 0;
+ }
+ tm.put(wordCursor, count + 1);
+ }
+ sc.close();
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ System.out.println("TreeMap full content:");
+ for (String wordCursor : tm.keySet()) {
+ System.out.println("Word \"" + wordCursor + "\" occured " + tm.get(wordCursor) + " times");
+ }
+
+ System.out.println("SortedMap content after the word \"milieu\":");
+ SortedMap<String, Integer> sm = tm.tailMap("milieu");
+ for (String wordCursor : sm.keySet()) {
+ System.out.println("Word \"" + wordCursor + "\" occured " + sm.get(wordCursor) + " times");
+ }
}
}