Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Exercise;
- import java.io.*;
- import java.util.HashMap;
- import java.util.Map;
- public class P06_WordCount {
- private static final String WORDS_INPUT_PATH = "src/Exercise/words.txt";
- private static final String TEXT_INPUT_PATH = "src/Exercise/text.txt";
- private static final String OUTPUT_PATH = "src/Exercise/output.txt";
- public static void main(String[] args) {
- try (BufferedReader readerWords = new BufferedReader(new FileReader(WORDS_INPUT_PATH));
- BufferedReader readerText = new BufferedReader(new FileReader(TEXT_INPUT_PATH));
- PrintWriter writer = new PrintWriter(OUTPUT_PATH)) {
- String[] words = readerWords.readLine().split("\\s+");
- Map<String, Integer> wordOccurrence = new HashMap<>();
- for (String word : words) {
- wordOccurrence.put(word, 0);
- }
- String[] text = readerText.readLine().split("\\s+");
- for (String word : text) {
- if (wordOccurrence.containsKey(word)) {
- int newCount = wordOccurrence.get(word) + 1;
- wordOccurrence.put(word, newCount);
- }
- }
- wordOccurrence
- .entrySet()
- .stream()
- .sorted((w1, w2) -> w2.getValue().compareTo(w1.getValue()))
- .forEach(w -> writer.println(String.format("%s - %d", w.getKey(), w.getValue())));
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement