From 5b722b3dcbf7dca301bf47335414f564518fbc47 Mon Sep 17 00:00:00 2001 From: ekaterinadidenko20 Date: Wed, 29 May 2019 21:24:37 +0300 Subject: [PATCH] qwer --- .../cet/javabasics/WarAndPeaceExercise.java | 35 ++++++++++++++----- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java b/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java index db16f2f..1289efd 100644 --- a/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java +++ b/src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java @@ -1,21 +1,40 @@ 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.*; 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 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(); + Charset kodir = Charset.forName("windows-1251"); + HashMap d = new HashMap<>(); + ArrayList text = ((ArrayList) Files.readAllLines(tome12Path,kodir)); + text.addAll(Files.readAllLines(tome34Path,kodir)); + String string = text.toString().toLowerCase().replaceAll("[^a-zа-я]", " "); + Arrays.stream(string.split(" ")).map(String::toLowerCase).filter(s->s.length()>3).forEach(s->{d.put(s, d.getOrDefault(s, 0) + 1);}); + List> list = new ArrayList<>(); + d.entrySet().stream().filter(pair -> pair.getValue() >= 10).forEach(list::add); + Collections.sort(list, new Comparator>(){ + @Override + public int compare(Map.Entry o1, Map.Entry o2){ + return ( o2.getValue() - o1.getValue() ) + == 0 ? + -o2.getKey().compareTo(o1.getKey()) + : + o2.getValue() - o1.getValue() ; + } + }); + StringBuilder stringBuilder = new StringBuilder(); + list.forEach(s -> stringBuilder.append(s.getKey() + " - " + s.getValue() + '\n')); + stringBuilder.deleteCharAt(stringBuilder.length()-1); + return stringBuilder.toString(); } } \ No newline at end of file