diff --git a/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java b/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java index db16f2f..628f8d9 100644 --- a/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java +++ b/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java @@ -1,21 +1,46 @@ package ru.ifmo.cet.javabasics; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; 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"); + final Charset charset = Charset.forName("windows-1251"); + List strings = Files.readAllLines(tome12Path, charset); + strings.addAll(Files.readAllLines(tome34Path, charset)); + List words = new ArrayList<>(); + + strings.stream().map(s->s.toLowerCase()).map(s -> s.replaceAll("[^a-zа-я]", " ")). + map(replace -> asList(replace.split(" "))).forEach(list-> words.addAll(list)); + List finalWords=words.stream().filter(s->s.length()>=4).collect(Collectors.toList()); + + Map dictionary=new LinkedHashMap<>(); + finalWords.forEach(key -> { + dictionary.put(key, dictionary.containsKey(key) ? dictionary.get(key) + 1 : 1); + }); + dictionary.entrySet().removeIf(entires->entires.getValue()<10); - // TODO map lowercased words to its amount in text and concatenate its entries. - // TODO Iff 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 iff needed. - // TODO Also omit any word with lengths less than 4 and frequency less than 10 + List> sorted_dictionaty = new ArrayList(dictionary.entrySet()); + sorted_dictionaty.sort(Map.Entry.comparingByKey()); + sorted_dictionaty.sort(Map.Entry.comparingByValue().reversed()); - throw new UnsupportedOperationException(); + String result=sorted_dictionaty.stream().map(entry->entry.getKey() + " - " + entry.getValue()).collect(Collectors.joining("\n")); + return result; + + + //throw new UnsupportedOperationException(); } + } \ No newline at end of file