Didart

Word Count

Jan 26th, 2023
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. package StreamsFilesAndDirectories4;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.util.*;
  8.  
  9. public class WordCount {
  10.     public static void main(String[] args) throws IOException {
  11.         Scanner scanner = new Scanner(System.in);
  12.  
  13.         String pathWords = "C:\\Users\\User\\Desktop\\Java Advanced - 10.01.23 - 13.09.22\\src\\StreamsFilesAndDirectories4\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\words.txt";
  14.  
  15.         Map<String, Integer> countWords = new HashMap<>();
  16.  
  17.         List<String> allLinesWithWords = Files.readAllLines(Path.of(pathWords));
  18.  
  19.         for (String lineWithWords : allLinesWithWords) {
  20.             Arrays.stream(lineWithWords.split("\\s+")).forEach(word -> {
  21.                 countWords.put(word, 0);
  22.             });
  23.         }
  24.  
  25.         String path = "C:\\Users\\User\\Desktop\\Java Advanced - 10.01.23 - 13.09.22\\src\\StreamsFilesAndDirectories4\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\text.txt";
  26.  
  27.         List<String> allLines = Files.readAllLines(Path.of(path));
  28.  
  29.         for (String line : allLines) {
  30.             Arrays.stream(line.split("\\s+"))
  31.                     .forEach(word -> {
  32.                         if (countWords.containsKey(word)) {
  33.                             int currentCount = countWords.get(word);
  34.                             countWords.put(word, currentCount + 1);
  35.                         }
  36.                     });
  37.         }
  38.         PrintWriter writer = new PrintWriter("results.txt");
  39.  
  40.         countWords.entrySet()
  41.                 .stream()
  42.                 .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
  43.                 .forEach(entry -> writer.println(entry.getKey() + " - " + entry.getValue()));
  44.  
  45.         writer.close();
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment