-
Notifications
You must be signed in to change notification settings - Fork 14
Java01. ДЗ 06, Сосин Иван, подгруппа 2 #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
iasawseen
wants to merge
6
commits into
java-course-au:05-streams
Choose a base branch
from
iasawseen:05-streams
base: 05-streams
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6c2e508
sosin 05-streams
iasawseen 49bd9cd
sosin 05-streams updated
iasawseen 49ff9a1
sosin 05-streams checkstyle fixed
iasawseen d736d3c
sosin 05-streams checkstyle fixed again
iasawseen 761e6f8
sosin 05-streams again
iasawseen d1b2cce
sosin 05-streams final, probably
iasawseen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,73 +1,114 @@ | ||
| package ru.spbau.mit; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.*; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.IntStream; | ||
| import java.util.stream.Stream; | ||
|
|
||
|
|
||
| public final class FirstPartTasks { | ||
|
|
||
| private FirstPartTasks() {} | ||
| // Список названий альбомов | ||
| public static List<String> allNames(Stream<Album> albums) { | ||
| throw new UnsupportedOperationException(); | ||
| return albums | ||
| .map(Album::getName) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Список названий альбомов, отсортированный лексикографически по названию | ||
| public static List<String> allNamesSorted(Stream<Album> albums) { | ||
| throw new UnsupportedOperationException(); | ||
| return albums | ||
| .map(Album::getName) | ||
| .sorted() | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Список треков, отсортированный лексикографически по названию, включающий все треки альбомов из 'albums' | ||
| public static List<String> allTracksSorted(Stream<Album> albums) { | ||
| throw new UnsupportedOperationException(); | ||
| return albums | ||
| .map(Album::getTracks) | ||
| .flatMap(Collection::stream) | ||
| .map(Track::getName) | ||
| .sorted() | ||
| .collect(Collectors.toList()); | ||
|
|
||
| } | ||
|
|
||
| // Список альбомов, в которых есть хотя бы один трек с рейтингом более 95, отсортированный по названию | ||
| public static List<Album> sortedFavorites(Stream<Album> s) { | ||
| throw new UnsupportedOperationException(); | ||
| final int threshold = 95; | ||
| return s | ||
| .filter(album -> album.getTracks() | ||
| .stream() | ||
| .filter(track -> track.getRating() > threshold).count() > 0) | ||
| .sorted(Comparator.comparing(Album::getName)) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Сгруппировать альбомы по артистам | ||
| public static Map<Artist, List<Album>> groupByArtist(Stream<Album> albums) { | ||
| throw new UnsupportedOperationException(); | ||
| return albums | ||
| .collect(Collectors.groupingBy(Album::getArtist)); | ||
| } | ||
|
|
||
| // Сгруппировать альбомы по артистам (в качестве значения вместо объекта 'Album' использовать его имя) | ||
| public static Map<Artist, List<String>> groupByArtistMapName(Stream<Album> albums) { | ||
| throw new UnsupportedOperationException(); | ||
| return albums | ||
| .collect(Collectors.groupingBy(Album::getArtist, | ||
| Collectors.mapping(Album::getName, Collectors.toList()))); | ||
| } | ||
|
|
||
| // Число повторяющихся альбомов в потоке | ||
| public static long countAlbumDuplicates(Stream<Album> albums) { | ||
| throw new UnsupportedOperationException(); | ||
| return albums | ||
| .collect(Collectors.groupingBy(c -> c, Collectors.counting())) | ||
| .entrySet() | ||
| .stream() | ||
| .filter(a -> a.getValue() > 1) | ||
| .count(); | ||
| } | ||
|
|
||
| // Альбом в котором максимум рейтинга минимален | ||
| // (если в альбоме нет ни одного трека, считать, что максимум рейтинга в нем --- 0) | ||
| public static Optional<Album> minMaxRating(Stream<Album> albums) { | ||
| throw new UnsupportedOperationException(); | ||
| return albums.min(Comparator.comparing(a -> a.getTracks() | ||
| .stream() | ||
| .mapToInt(Track::getRating) | ||
| .max() | ||
| .orElse(0))); | ||
| } | ||
|
|
||
| // Список альбомов, отсортированный по убыванию среднего рейтинга его треков (0, если треков нет) | ||
| public static List<Album> sortByAverageRating(Stream<Album> albums) { | ||
| throw new UnsupportedOperationException(); | ||
| return albums | ||
| .sorted(Comparator.comparing( | ||
| a -> ((Album) a).getTracks().stream() | ||
| .mapToInt(Track::getRating) | ||
| .average() | ||
| .orElse(0)).reversed()) | ||
| .collect(Collectors.toList()); | ||
|
|
||
| } | ||
|
|
||
| // Произведение всех чисел потока по модулю 'modulo' | ||
| // (все числа от 0 до 10000) | ||
| public static int moduloProduction(IntStream stream, int modulo) { | ||
| throw new UnsupportedOperationException(); | ||
| return stream | ||
| .reduce(1, (a, b) -> a * b % modulo); | ||
| } | ||
|
|
||
| // Вернуть строку, состояющую из конкатенаций переданного массива, и окруженную строками "<", ">" | ||
| // см. тесты | ||
| public static String joinTo(String... strings) { | ||
| throw new UnsupportedOperationException(); | ||
| return Stream.of(strings) | ||
| .collect(Collectors.joining(", ", "<", ">")); | ||
| } | ||
|
|
||
| // Вернуть поток из объектов класса 'clazz' | ||
| public static <R> Stream<R> filterIsInstance(Stream<?> s, Class<R> clazz) { | ||
| throw new UnsupportedOperationException(); | ||
| return s | ||
| .filter(clazz::isInstance) | ||
| .map(a -> (R) a); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. clazz::cast |
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,34 +1,67 @@ | ||
| package ru.spbau.mit; | ||
|
|
||
|
|
||
| import java.io.IOException; | ||
| import java.io.UncheckedIOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Paths; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.Stream; | ||
|
|
||
|
|
||
| public final class SecondPartTasks { | ||
|
|
||
| private SecondPartTasks() {} | ||
|
|
||
| // Найти строки из переданных файлов, в которых встречается указанная подстрока. | ||
| public static List<String> findQuotes(List<String> paths, CharSequence sequence) { | ||
| throw new UnsupportedOperationException(); | ||
| return paths.stream() | ||
| .flatMap(path -> { | ||
| try { | ||
| return Files.lines(Paths.get(path)); | ||
| } catch (IOException e) { | ||
| throw new UncheckedIOException(e); | ||
| } | ||
| }) | ||
| .filter(str -> str.contains(sequence)) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // В квадрат с длиной стороны 1 вписана мишень. | ||
| // Стрелок атакует мишень и каждый раз попадает в произвольную точку квадрата. | ||
| // Надо промоделировать этот процесс с помощью класса java.util.Random и посчитать, | ||
| // какова вероятность попасть в мишень. | ||
| public static double piDividedBy4() { | ||
| throw new UnsupportedOperationException(); | ||
| final long trials = 6666666; | ||
| final double radius = 0.5; | ||
|
|
||
| return Stream | ||
| .generate(() -> Math.pow(Math.random() - radius, 2) | ||
| + Math.pow(Math.random() - radius, 2) <= Math.pow(radius, 2)) | ||
| .limit(trials) | ||
| .filter(a -> a) | ||
| .count() / (double) trials; | ||
| } | ||
|
|
||
| // Дано отображение из имени автора в список с содержанием его произведений. | ||
| // Надо вычислить, чья общая длина произведений наибольшая. | ||
| public static String findPrinter(Map<String, List<String>> compositions) { | ||
| throw new UnsupportedOperationException(); | ||
| return compositions | ||
| .entrySet() | ||
| .stream() | ||
| .max(Comparator.comparing(entry -> entry.getValue().stream().mapToLong(String::length).sum())) | ||
| .get().getKey(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. warning, который желательно избежать |
||
| } | ||
|
|
||
| // Вы крупный поставщик продуктов. Каждая торговая сеть делает вам заказ в виде Map<Товар, Количество>. | ||
| // Необходимо вычислить, какой товар и в каком количестве надо поставить. | ||
| public static Map<String, Integer> calculateGlobalOrder(List<Map<String, Integer>> orders) { | ||
| throw new UnsupportedOperationException(); | ||
| return orders | ||
| .stream() | ||
| .flatMap(map -> map.entrySet().stream()) | ||
| .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.summingInt(Map.Entry::getValue))); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
см anyMatch