nikeza

6.Word Count

Oct 4th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.38 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.nio.file.Files;
  6. import java.nio.file.Paths;
  7. import java.util.*;
  8. import java.util.stream.Collectors;
  9.  
  10. public class streams1_Exercises_6Word_Count {
  11.     public static void main(String[] args) {
  12.  
  13.         String input = "C:\\Users\\kk\\Desktop\\SoftUni\\Java Advanced\\Lections\\" +
  14.                 "04. Java-Exercises_Advanced-Streams-Files-and-Directories-Resources (1)\\" +
  15.                 "04. Java-Advanced-Files-and-Streams-Exercises-Resources\\";
  16.         String pathIn = input + "words.txt";
  17.         String pathInTwo = input + "text.txt";
  18.  
  19.         String pathOut = input + "wordsResults.txt";
  20.  
  21.  
  22.         try {
  23.             try (BufferedReader bf = Files.newBufferedReader(Paths.get(pathIn))) {
  24.                 try (BufferedReader bfTwo = Files.newBufferedReader(Paths.get(pathInTwo))) {
  25.                     try (PrintWriter write = new PrintWriter(pathOut)) {
  26.                        
  27.                         List<String> text = Arrays.stream(bf.readLine().split("\\s+"))
  28.                                 .collect(Collectors.toList());
  29.                        
  30.                         Map<String, Integer> word = new HashMap<>();
  31.                        
  32.                         for (String value : text) {
  33.                             word.putIfAbsent(value, 0);
  34.                         }
  35.  
  36.                         String readBfTwo = bfTwo.readLine();
  37.                         List<String> textTwo = new ArrayList<>();
  38.  
  39.                         while (readBfTwo != null) {
  40.                             String[] textArr = readBfTwo.split("\\s+");
  41.  
  42.                             for (String s : textArr) {
  43.                                 if (word.containsKey(s)) {
  44.                                     word.put(s, word.get(s) + 1);
  45.                                 }
  46.                             }
  47.  
  48.                             readBfTwo = bfTwo.readLine();
  49.                         }
  50.  
  51.                         word.entrySet().stream().sorted((f, s) -> s.getValue()
  52.                                 .compareTo(f.getValue())).forEach(e ->
  53.                                 write.printf("%s - %d%n", e.getKey(), e.getValue()));
  54.  
  55.  
  56.                     }
  57.                 }
  58.             }
  59.         } catch (IOException e) {
  60.             e.printStackTrace();
  61.         }
  62.  
  63.     }
  64.  
  65. }
Add Comment
Please, Sign In to add comment