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