-
Notifications
You must be signed in to change notification settings - Fork 0
Java02. ДЗ 03, Кравченко Юрий, подгруппа 2 #4
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
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package sp; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.List; | ||
|
|
||
| public class Album { | ||
|
|
||
| private final String name; | ||
| private final List<Track> tracks; | ||
| private final Artist artist; | ||
|
|
||
| public Album(Artist artist, String name, Track... tracks) { | ||
| this.name = name; | ||
| this.tracks = Arrays.asList(tracks); | ||
| this.artist = artist; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public List<Track> getTracks() { | ||
| return tracks; | ||
| } | ||
|
|
||
| public Artist getArtist() { | ||
| return artist; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| package sp; | ||
|
|
||
| public class Artist { | ||
|
|
||
| private final String name; | ||
|
|
||
| public Artist(String name) { | ||
| this.name = name; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| package sp; | ||
|
|
||
| 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) { | ||
| return albums.map(Album::getName).collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Список названий альбомов, отсортированный лексикографически по названию | ||
| public static List<String> allNamesSorted(Stream<Album> albums) { | ||
| return albums | ||
| .map(Album::getName) | ||
| .sorted() | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Список треков, отсортированный лексикографически по названию, включающий все треки альбомов из 'albums' | ||
| public static List<String> allTracksSorted(Stream<Album> albums) { | ||
| return albums | ||
| .map(Album::getTracks) | ||
| .flatMap(List::stream) | ||
| .map(Track::getName) | ||
| .sorted() | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Список альбомов, в которых есть хотя бы один трек с рейтингом более 95, отсортированный по названию | ||
| public static List<Album> sortedFavorites(Stream<Album> albums) { | ||
| return albums | ||
| .filter(album -> album | ||
| .getTracks() | ||
| .stream() | ||
| .filter(track -> track.getRating() > 95) | ||
| .count() > 0) | ||
| .sorted(Comparator.comparing(Album::getName)) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Сгруппировать альбомы по артистам | ||
| public static Map<Artist, List<Album>> groupByArtist(Stream<Album> albums) { | ||
| return albums | ||
| .collect(Collectors.groupingBy(Album::getArtist)); | ||
| } | ||
|
|
||
| // Сгруппировать альбомы по артистам (в качестве значения вместо объекта 'Artist' использовать его имя) | ||
| public static Map<Artist, List<String>> groupByArtistMapName(Stream<Album> albums) { | ||
| return albums | ||
| .collect(Collectors.groupingBy( | ||
| Album::getArtist, | ||
| Collectors.mapping( | ||
| Album::getName, | ||
| Collectors.toList()))); | ||
| } | ||
|
|
||
| // Число повторяющихся альбомов в потоке | ||
| public static long countAlbumDuplicates(Stream<Album> albums) { | ||
| return albums | ||
| .collect(Collectors.groupingBy(a -> 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. a -> a => Function.identity() |
||
| .values() | ||
| .stream() | ||
| .filter(l -> l.size() > 1) | ||
| .count(); | ||
| } | ||
|
|
||
| // Альбом, в котором максимум рейтинга минимален | ||
| // (если в альбоме нет ни одного трека, считать, что максимум рейтинга в нем --- 0) | ||
| public static Optional<Album> minMaxRating(Stream<Album> albums) { | ||
| return albums | ||
| .min(Comparator.comparingInt(a -> a | ||
| .getTracks() | ||
| .stream() | ||
| .map(Track::getRating) | ||
| .max(Comparator.naturalOrder()) | ||
|
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. можно написать так: mapToInt(Track::getRating).max() |
||
| .orElse(0))); | ||
| } | ||
|
|
||
| // Список альбомов, отсортированный по убыванию среднего рейтинга его треков (0, если треков нет) | ||
| public static List<Album> sortByAverageRating(Stream<Album> albums) { | ||
| return albums | ||
| .sorted(Comparator.comparingDouble((Album a) -> a | ||
| .getTracks() | ||
| .stream() | ||
| .mapToInt(Track::getRating) | ||
| .average().orElse(0)).reversed()) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Произведение всех чисел потока по модулю 'modulo' | ||
| // (все числа от 0 до 10000) | ||
| public static int moduloProduction(IntStream stream, int modulo) { | ||
| return stream.reduce(1, (a, b) -> a * b % modulo); | ||
| } | ||
|
|
||
| // Вернуть строку, состояющую из конкатенаций переданного массива, и окруженную строками "<", ">" | ||
| // см. тесты | ||
| public static String joinTo(String... strings) { | ||
| return Arrays.stream(strings) | ||
| .collect(Collectors.joining(", ", "<", ">")); | ||
| } | ||
|
|
||
| // Вернуть поток из объектов класса 'clazz' | ||
| public static <R> Stream<R> filterIsInstance(Stream<?> s, Class<R> clazz) { | ||
| return (Stream<R>) s.filter(o -> clazz.isAssignableFrom(o.getClass())); | ||
|
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.
|
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| package sp; | ||
|
|
||
| import java.io.IOException; | ||
| 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.Random; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.DoubleStream; | ||
| import java.util.stream.Stream; | ||
|
|
||
| public final class SecondPartTasks { | ||
|
|
||
| private SecondPartTasks() {} | ||
|
|
||
| // Найти строки из переданных файлов, в которых встречается указанная подстрока. | ||
| public static List<String> findQuotes(List<String> paths, CharSequence sequence) { | ||
| return paths | ||
| .stream() | ||
| .flatMap(p -> { | ||
| try { | ||
| return Files.lines(Paths.get(p)); | ||
| } catch (IOException e) { | ||
| return Stream.empty(); | ||
| } | ||
| }) | ||
| .filter(s -> s.contains(sequence)) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // В квадрат с длиной стороны 1 вписана мишень. | ||
| // Стрелок атакует мишень и каждый раз попадает в произвольную точку квадрата. | ||
| // Надо промоделировать этот процесс с помощью класса java.util.Random и посчитать, какова вероятность попасть в мишень. | ||
| public static double piDividedBy4() { | ||
| Random random = new Random(); | ||
| return Double.valueOf(DoubleStream | ||
| .generate(() -> Math.pow(random.nextDouble() - 0.5, 2) + Math.pow(random.nextDouble() - 0.5, 2)) | ||
| .limit(10000000) | ||
| .filter(l -> l <= Math.pow(0.5, 2)) | ||
| .count()) / 10000000; | ||
| } | ||
|
|
||
| // Дано отображение из имени автора в список с содержанием его произведений. | ||
| // Надо вычислить, чья общая длина произведений наибольшая. | ||
| public static String findPrinter(Map<String, List<String>> compositions) { | ||
| return compositions | ||
| .entrySet() | ||
| .stream() | ||
| .sorted(Comparator | ||
| .comparingInt((Map.Entry<String, List<String>> e) -> e.getValue() | ||
| .stream() | ||
| .mapToInt(String::length) | ||
| .sum()) | ||
| .reversed()) | ||
| .map(Map.Entry::getKey) | ||
| .findFirst() | ||
| .orElse(""); | ||
|
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. как показатель отсутствия результата лучше возвращать null |
||
| } | ||
|
|
||
| // Вы крупный поставщик продуктов. Каждая торговая сеть делает вам заказ в виде Map<Товар, Количество>. | ||
| // Необходимо вычислить, какой товар и в каком количестве надо поставить. | ||
| public static Map<String, Integer> calculateGlobalOrder(List<Map<String, Integer>> orders) { | ||
| return orders | ||
| .stream() | ||
| .flatMap(m -> m.entrySet().stream()) | ||
| .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.summingInt(Map.Entry::getValue))); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package sp; | ||
|
|
||
| public class Track { | ||
|
|
||
| private final String name; | ||
| private final int rating; | ||
|
|
||
| public Track(String name, int rating) { | ||
| this.name = name; | ||
| this.rating = rating; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public int getRating() { | ||
| return rating; | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.
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.
filter(...).count() > 0 => anyMatch