Small code cleanup.
[Project_POO.git] / exo5 / Main.java
index 4075cbc4ed5997f2f9c18bf6b6ec1b59a5fba719..f8fac79d30962692271303ab403857440c90a36e 100644 (file)
@@ -1,3 +1,10 @@
+import java.io.File;
+import java.util.Scanner;
+import java.io.IOException;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.SortedMap;
+import java.util.stream.Collectors;
 
 class Main {
 
@@ -6,6 +13,53 @@ class Main {
      * @param String[] args main() function arguments array
      */
     public static void main(String[] args) {
+        // default TreeMap comparator keep alphabetical order
+        // NOTE: words comparaison is case insensitive and punctuation aware
+        TreeMap<String, Integer> tm = new TreeMap<String, Integer>(new StrComparator());
+        // NOTE: words comparaison is case sensitive and punctuation aware
+        //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();
+                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 of words inferior to the word \"milieu\":");
+        SortedMap<String, Integer> sm = tm.headMap("milieu");
+        for (String wordCursor : sm.keySet()) {
+            System.out.println("Word \"" + wordCursor + "\" occured " + sm.get(wordCursor) + " times");
+        }
+
+        System.out.println("Map content of duplicates inferior to the word \"milieu\":");
+        Map<String, Integer> m1 = tm.entrySet().stream()
+            .filter(map -> map.getKey().compareTo("milieu") < 0 && map.getValue() == 2)
+            .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
+        for (String wordCursor : m1.keySet()) {
+            System.out.println("Word \"" + wordCursor + "\" occured " + sm.get(wordCursor) + " times");
+        }
+
+        System.out.println("Map content of duplicates with occurence between 2 and 5:");
+        Map<String, Integer> m2 = tm.entrySet().stream()
+            .filter(map -> map.getValue() >= 2 && map.getValue() <= 5)
+            .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
+        for (String wordCursor : m2.keySet()) {
+            System.out.println("Word \"" + wordCursor + "\" occured " + sm.get(wordCursor) + " times");
+        }
     }
 }