exo5: add filtred maps from the original tree map.
[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.Map;
5 import java.util.TreeMap;
6 import java.util.SortedMap;
7 import java.util.stream.Collectors;
8
9 class Main {
10
11 /**
12 * The main() function
13 * @param String[] args main() function arguments array
14 */
15 public static void main(String[] args) {
16 // default TreeMap comparator keep alphabetical order
17 // NOTE: words comparaison is case insensitive and punctuation aware
18 TreeMap<String, Integer> tm = new TreeMap<String, Integer>(new StrComparator());
19 // NOTE: words comparaison is case sensitive and punctuation aware
20 //TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
21 File f = new File("test_file.txt");
22 try {
23 Scanner sc = new Scanner(f);
24 while (sc.hasNext()) {
25 String wordCursor = sc.next();
26
27 Integer count = tm.get(wordCursor);
28 if (count == null) {
29 count = 0;
30 }
31 tm.put(wordCursor, count + 1);
32 }
33 sc.close();
34 }
35 catch (IOException e) {
36 e.printStackTrace();
37 }
38
39 System.out.println("TreeMap full content:");
40 for (String wordCursor : tm.keySet()) {
41 System.out.println("Word \"" + wordCursor + "\" occured " + tm.get(wordCursor) + " times");
42 }
43
44 System.out.println("SortedMap content of words inferior to the word \"milieu\":");
45 SortedMap<String, Integer> sm = tm.headMap("milieu");
46 for (String wordCursor : sm.keySet()) {
47 System.out.println("Word \"" + wordCursor + "\" occured " + sm.get(wordCursor) + " times");
48 }
49
50 System.out.println("Map content of duplicates inferior to the word \"milieu\":");
51 Map<String, Integer> m1 = tm.entrySet().stream()
52 .filter(map -> map.getKey().compareTo("milieu") < 0 && map.getValue() == 2)
53 .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
54 for (String wordCursor : m1.keySet()) {
55 System.out.println("Word \"" + wordCursor + "\" occured " + sm.get(wordCursor) + " times");
56 }
57
58 System.out.println("Map content of duplicates with occurence between 2 and 5:");
59 Map<String, Integer> m2 = tm.entrySet().stream()
60 .filter(map -> map.getValue() >= 2 && map.getValue() <= 5)
61 .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
62 for (String wordCursor : m2.keySet()) {
63 System.out.println("Word \"" + wordCursor + "\" occured " + sm.get(wordCursor) + " times");
64 }
65 }
66 }