Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package StreamsFilesAndDirectories4;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.util.*;
- public class WordCount {
- public static void main(String[] args) throws IOException {
- Scanner scanner = new Scanner(System.in);
- 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";
- Map<String, Integer> countWords = new HashMap<>();
- List<String> allLinesWithWords = Files.readAllLines(Path.of(pathWords));
- for (String lineWithWords : allLinesWithWords) {
- Arrays.stream(lineWithWords.split("\\s+")).forEach(word -> {
- countWords.put(word, 0);
- });
- }
- 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";
- List<String> allLines = Files.readAllLines(Path.of(path));
- for (String line : allLines) {
- Arrays.stream(line.split("\\s+"))
- .forEach(word -> {
- if (countWords.containsKey(word)) {
- int currentCount = countWords.get(word);
- countWords.put(word, currentCount + 1);
- }
- });
- }
- PrintWriter writer = new PrintWriter("results.txt");
- countWords.entrySet()
- .stream()
- .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
- .forEach(entry -> writer.println(entry.getKey() + " - " + entry.getValue()));
- writer.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment