exo5: add a SortedMap from the TreeMap.
[Project_POO.git] / exo5 / Main.java
1 import java.io.File;
2 import java.util.Scanner;
3 import java.io.IOException;
4 import java.util.TreeMap;
5 import java.util.SortedMap;
6
7 class Main {
8
9 /**
10 * The main() function
11 * @param String[] args main() function arguments array
12 */
13 public static void main(String[] args) {
14 //TreeMap<String, Integer> tm = new TreeMap<String, Integer>(new StrComparator());
15 // default TreeMap comparator keep alphabetical order
16 TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
17 File f = new File("test_file.txt");
18 try {
19 Scanner sc = new Scanner(f);
20 while (sc.hasNext()) {
21 String wordCursor = sc.next();
22 //NOTE: words comparaison is case sensitive and punctuation aware
23 Integer count = tm.get(wordCursor);
24 if (count == null) {
25 count = 0;
26 }
27 tm.put(wordCursor, count + 1);
28 }
29 sc.close();
30 }
31 catch (IOException e) {
32 e.printStackTrace();
33 }
34
35 System.out.println("TreeMap full content:");
36 for (String wordCursor : tm.keySet()) {
37 System.out.println("Word \"" + wordCursor + "\" occured " + tm.get(wordCursor) + " times");
38 }
39
40 System.out.println("SortedMap content after the word \"milieu\":");
41 SortedMap<String, Integer> stm = tm.tailMap("milieu");
42 for (String wordCursor : stm.keySet()) {
43 System.out.println("Word \"" + wordCursor + "\" occured " + stm.get(wordCursor) + " times");
44 }
45 }
46 }