Advertisement
A_Marinov

Untitled

Jan 31st, 2021
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. package Exercise;
  2.  
  3. import java.io.*;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. public class P06_WordCount {
  8.     private static final String WORDS_INPUT_PATH = "src/Exercise/words.txt";
  9.     private static final String TEXT_INPUT_PATH = "src/Exercise/text.txt";
  10.     private static final String OUTPUT_PATH = "src/Exercise/output.txt";
  11.  
  12.     public static void main(String[] args) {
  13.         try (BufferedReader readerWords = new BufferedReader(new FileReader(WORDS_INPUT_PATH));
  14.              BufferedReader readerText = new BufferedReader(new FileReader(TEXT_INPUT_PATH));
  15.              PrintWriter writer = new PrintWriter(OUTPUT_PATH)) {
  16.  
  17.             String[] words = readerWords.readLine().split("\\s+");
  18.             Map<String, Integer> wordOccurrence = new HashMap<>();
  19.             for (String word : words) {
  20.                 wordOccurrence.put(word, 0);
  21.             }
  22.  
  23.             String[] text = readerText.readLine().split("\\s+");
  24.             for (String word : text) {
  25.                 if (wordOccurrence.containsKey(word)) {
  26.                     int newCount = wordOccurrence.get(word) + 1;
  27.                     wordOccurrence.put(word, newCount);
  28.                 }
  29.             }
  30.             wordOccurrence
  31.                     .entrySet()
  32.                     .stream()
  33.                     .sorted((w1, w2) -> w2.getValue().compareTo(w1.getValue()))
  34.                     .forEach(w -> writer.println(String.format("%s - %d", w.getKey(), w.getValue())));
  35.  
  36.         } catch (IOException ioe) {
  37.             ioe.printStackTrace();
  38.         }
  39.     }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement