diff --git a/.idea/IFMO_JAVA_Basics_20182009.iml b/.idea/IFMO_JAVA_Basics_20182009.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/IFMO_JAVA_Basics_20182009.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java b/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java index db16f2f..662d4aa 100644 --- a/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java +++ b/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java @@ -2,20 +2,38 @@ import java.nio.file.Path; import java.nio.file.Paths; - +import java.nio.file.Files; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; 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)); + Map dictionary = new TreeMap(); - // 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 - - throw new UnsupportedOperationException(); + String text = strings.toString().replaceAll("[^a-zA-Zа-яА-Я]", " ").toLowerCase(); + Stream reading = Stream.of(text.split(" ")); + reading.filter((word) -> word.length() >= 4).forEach((word) -> { + dictionary.merge(word, 1, (oldWal, newWal) -> oldWal+newWal); + }); + List> forSorting = + new LinkedList(dictionary.entrySet()); + forSorting.sort(Map.Entry.comparingByKey()); + forSorting.sort(Map.Entry.comparingByValue().reversed()); + StringBuffer result = new StringBuffer(); + forSorting.stream().filter(counter -> counter.getValue()>=10) + .forEach(counter ->{ + result.append(counter.getKey()+" - "+counter.getValue()+"\n"); + }); + return result.toString().substring(0, result.length()-1); + //throw new UnsupportedOperationException(); } - } \ No newline at end of file