From 8bba363cf8f87719a861a39d385752e47c0cf019 Mon Sep 17 00:00:00 2001 From: asvarish <42956531+asvarish@users.noreply.github.com> Date: Fri, 31 May 2019 21:16:08 +0300 Subject: [PATCH] Update WarAndPeaceExercise.java --- .../cet/javabasics/WarAndPeaceExercise.java | 63 ++++++++++++++++--- 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java b/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java index 1ff35c2..3d70880 100644 --- a/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java +++ b/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java @@ -1,21 +1,64 @@ package ru.ifmo.cet.javabasics; -import java.nio.file.Path; -import java.nio.file.Paths; + import java.nio.file.Path; + import java.nio.file.Paths; + + import java.io.IOException; + import java.nio.charset.Charset; + import java.nio.file.Files; + import java.util.*; public class WarAndPeaceExercise { - public static String warAndPeace() { + public static String warAndPeace() throws IOException { final Path tome12Path = Paths.get("src", "main", "resources", "WAP12.txt"); final Path tome34Path = Paths.get("src", "main", "resources", "WAP34.txt"); - // TODO map lowercased words to its amount in text and concatenate its entries. - // TODO If word "котик" occurred in text 23 times then its entry would be "котик - 23\n". - // TODO Entries in final String should be also sorted by amount and then in alphabetical order if needed. - // TODO Also omit any word with lengths less than 4 and frequency less than 10 + List rows; - throw new UnsupportedOperationException(); - } + rows = Files.readAllLines(tome12Path, Charset.forName("windows-1251")); + rows.addAll(Files.readAllLines(tome34Path, Charset.forName("windows-1251"))); + String[] words = Arrays.toString(rows.toArray()).toLowerCase().split("[^a-zа-я]+"); + + Map wordsMap = new HashMap<>(); + + for (String word : words) { + if (word.length() >= 4) { + wordsMap.put(word, wordsMap.getOrDefault(word, 0) + 1); + } + } + + SortedSet> sorted = new TreeSet<>( + + + new Comparator>() { + public int compare(Map.Entry a, Map.Entry b) { + + if (a.getValue().equals(b.getValue())) { + return a.getKey().compareTo(b.getKey()); + } + else { + return b.getValue() - a.getValue(); + } + } + } + ); -} \ No newline at end of file + + sorted.addAll(wordsMap.entrySet()); + + + StringBuilder result = new StringBuilder(); + + + for (Map.Entry entry : sorted) { + + if (entry.getValue() >= 10) { + result.append(entry.getKey()).append(" - ").append(entry.getValue()).append("\n"); + } + } + + return result.deleteCharAt(result.length()-1).toString(); + } +}