Advertisement
Guest User

Word COunt

a guest
Jan 29th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. import java.io.*;
  2. import java.nio.file.Files;
  3. import java.nio.file.Path;
  4. import java.nio.file.Paths;
  5. import java.util.Arrays;
  6. import java.util.LinkedHashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.stream.Collectors;
  10.  
  11. public class WordCount {
  12.  
  13. public static void main(String[] args) {
  14.  
  15. String firstUrl = "C:\\Users\\ste4o\\Desktop\\words.txt";
  16. String secondUrl = "C:\\Users\\ste4o\\Desktop\\text.txt";
  17. Path firstPath = Paths.get(firstUrl);
  18. Path secondPath = Paths.get(secondUrl);
  19. String pathOut = System.getProperty("user.dir") + "/resources/output.txt";
  20.  
  21. try (PrintWriter writer = new PrintWriter(pathOut)) {
  22. List<String> firstListOfLines = Files.readAllLines(firstPath);
  23. List<String> secondListOfLines = Files.readAllLines(secondPath);
  24.  
  25. List<String> firstListOfWords = Arrays.stream(firstListOfLines.get(0).split("\\s+"))
  26. .collect(Collectors.toList());
  27.  
  28. Map<String, Integer> wordCount = new LinkedHashMap<>();
  29. for (String word : firstListOfWords) {
  30. wordCount.putIfAbsent(word, 0);
  31. }
  32.  
  33. List<String> secondListOfWords = Arrays.stream(secondListOfLines.get(0).split("\\s+"))
  34. .collect(Collectors.toList());
  35.  
  36. for (String word : secondListOfWords) {
  37. if (wordCount.containsKey(word)) {
  38. int newCount = wordCount.get(word) + 1;
  39. wordCount.put(word, newCount);
  40. }
  41. }
  42.  
  43. wordCount.forEach((k, v) -> writer.println(String.format("%s - %d", k, v)));
  44. // wordCount.forEach((k, v) -> System.out.printf("%s - %d%n", k, v));
  45.  
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement