-
Notifications
You must be signed in to change notification settings - Fork 0
lesson12 #12
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
mikhail-gen
wants to merge
3
commits into
master
Choose a base branch
from
lesson12
base: master
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
lesson12 #12
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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 |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| package functional; | ||
|
|
||
| import java.util.*; | ||
| import java.util.function.*; | ||
|
|
||
| public class Functional { | ||
|
|
||
| public static void main(String[] args) { | ||
|
|
||
| // 1. Predicate<String>: строка не пуста и длиннее 3 символов | ||
| Predicate<String> validString = s -> s != null && s.length() > 3; | ||
|
|
||
| // 2. Function<String, Integer>: возвращает длину строки | ||
| Function<String, Integer> getStringLength = s -> s.length(); | ||
| Function<String, Integer> stringLength = String::length; | ||
|
|
||
|
|
||
| // 3. Supplier<UUID>: возвращает новый UUID | ||
| Supplier<UUID> randomUUID = () -> UUID.randomUUID(); | ||
|
|
||
| // 4. Consumer<String>: выводит строку в upper case | ||
| Consumer<String> stringToUpperCase = s -> s.toUpperCase(); | ||
|
|
||
| // 5. BiFunction<Integer, Integer, Integer>: сумма двух чисел | ||
| BiFunction<Integer, Integer, Integer> sumTwoIntegers = (i, j) -> Integer.sum(i, j); | ||
|
|
||
| // 6. Объединение trim и toUpperCase | ||
| Function<String, String> trim = String::trim; | ||
| Function<String, String> toUpperCase = String::toUpperCase; | ||
| Function<String, String> trimAndThenToUpperCase = trim.andThen(toUpperCase); | ||
|
|
||
|
|
||
| Function<String, String> trimThenUpper = trim.andThen(toUpperCase); | ||
|
|
||
| // 7. Объединение двух Consumer | ||
| Consumer<String> printString = System.out::println; | ||
| Consumer<String> printLength = s -> System.out.println(s.length()); | ||
| Consumer<String> printStringAndThenPintLength = printString.andThen(printLength); | ||
|
|
||
|
|
||
| // 8. Predicate<Integer>: isEven и isPositive, потом "нечётное или отрицательное" | ||
| Predicate<Integer> isEven = x -> x % 2 == 0; | ||
| Predicate<Integer> isPositive = x -> x > 0; | ||
| Predicate<Integer> oddOrNegative = isEven.negate().or(isPositive.negate()); | ||
|
|
||
|
|
||
| // 9. BiFunction + Function через andThen() | ||
| BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b; | ||
| Function<Integer, String> toStr = x -> x.toString(); | ||
| BiFunction<Integer, Integer, String> multiplyThenStr = multiply.andThen(toStr); | ||
|
|
||
| // 10. UnaryOperator<String>: добавляет "!!!" | ||
| UnaryOperator<String> adsExclaims = s -> s = s + "!!!"; | ||
| } | ||
|
|
||
| // 11. Метод filter(List<T> list, Predicate<T> predicate) | ||
| public static <T> List<T> filter(List<T> list, Predicate<T> predicate) { | ||
| List<T> result = new ArrayList<>(); | ||
| for (T item : list) { | ||
| if (predicate.test(item)) { | ||
| result.add(item); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| // 12. Метод map(List<T> list, Function<T, R> mapper) | ||
| public static <T, R> List<R> map(List<T> list, Function<T, R> mapper) { | ||
| List<R> resultList = new ArrayList<>(); | ||
| for (T item : list) { | ||
| resultList.add(mapper.apply(item)); | ||
| } | ||
| return resultList; | ||
| } | ||
|
|
||
| // преобразуй List<String> в List<Integer> (длины строк). | ||
| public static List<Integer> mapStringLengthsToIntegers(List<String> list) { | ||
| List<Integer> resultIntegerList = new ArrayList<>(); | ||
| Function<String, Integer> getStringLength = s -> s.length(); | ||
| resultIntegerList = map(list, getStringLength); | ||
| return resultIntegerList; | ||
| } | ||
|
|
||
| // 13. Метод forEach(List<T> list, Consumer<T> consumer) | ||
| public static <T> void forEach(List<T> list, Consumer<T> consumer) { | ||
| for (T t : list) { | ||
| consumer.accept(t); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| // 14. Метод generate(Supplier<T> supplier, int n) | ||
| public static <T> List<T> generate(Supplier<T> supplier, int n) { | ||
| List<T> result = new ArrayList<>(); | ||
| for (int i = 0; i < n; i++) { | ||
| result.add(supplier.get()); | ||
| } | ||
| return result; | ||
| } | ||
| } |
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 |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| package streams; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Arrays; | ||
| import java.util.Comparator; | ||
| import java.util.HashMap; | ||
| import java.util.HashSet; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class Fors { | ||
| public static void main(String[] args) { | ||
| // Дан список чисел. Оставь только чётные и выведи их квадраты. | ||
| List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6); | ||
| List<Integer> result = new ArrayList<>(); | ||
| for (int n : numbers) { | ||
| if (n % 2 == 0) { | ||
| result.add(n * n); | ||
| } | ||
| } | ||
|
|
||
| // Подсчитай, сколько строк в списке длиннее 5 символов. | ||
| List<String> words = List.of("apple", "banana", "pear", "pineapple"); | ||
| int count = 0; | ||
| for (String s : words) { | ||
| if (s.length() > 5) { | ||
| count++; | ||
| } | ||
| } | ||
|
|
||
| // Найди максимальное и минимальное число в списке с помощью Stream API. | ||
| List<Integer> nums = List.of(10, 2, 33, 4, 25); | ||
| int min = nums.get(0); | ||
| int max = nums.get(0); | ||
| for (int n : nums) { | ||
| if (n < min) min = n; | ||
| if (n > max) max = n; | ||
| } | ||
|
|
||
| // Посчитай среднюю длину строк в списке. | ||
| List<String> names = List.of("Alice", "Bob", "Charlie", "David"); | ||
| int totalLength = 0; | ||
| for (String s : names) { | ||
| totalLength += s.length(); | ||
| } | ||
| var average = totalLength / names.size(); | ||
|
|
||
|
|
||
| // Удали дубликаты и отсортируй строки по длине. | ||
| List<String> input = List.of("apple", "pear", "apple", "banana", "pear"); | ||
| Set<String> unique = new HashSet<>(input); | ||
|
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.
|
||
| List<String> result2 = new ArrayList<>(unique); | ||
| result2.sort(Comparator.comparingInt(String::length)); | ||
|
|
||
| // Преобразуй список строк в Map: ключ — строка, значение — длина. | ||
| List<String> fruits = List.of("apple", "banana", "kiwi"); | ||
| var newMap = new HashMap<>(); | ||
| for (String s : fruits) { | ||
| newMap.put(s, s.length()); | ||
| } | ||
|
|
||
| // Сгруппируй имена по первой букве. | ||
| List<String> names2 = List.of("Alice", "Andrew", "Bob", "Charlie", "Catherine"); | ||
| Map<Character, List<String>> grouped = new HashMap<>(); | ||
| for (String s : names2) { | ||
| char first = s.charAt(0); | ||
| grouped.computeIfAbsent(first, k -> new ArrayList<>()).add(s); | ||
| } | ||
|
|
||
| // Собери список имён в одну строку через запятую. | ||
| List<String> names3 = List.of("Tom", "Jerry", "Spike"); | ||
| StringBuilder stringBuilder = new StringBuilder(); | ||
| for (int i = 0; i < names3.size(); i++) { | ||
| stringBuilder.append(names3.get(i)); | ||
| if (i < names3.size() - 1) { | ||
| stringBuilder.append(", "); | ||
| } | ||
| } | ||
| String oneStringOfNames = stringBuilder.toString(); | ||
|
|
||
| // Из списка предложений получить список всех слов. | ||
| List<String> sentences = List.of("Java is cool", "Streams are powerful"); | ||
| List<String> words2 = new ArrayList<>(); | ||
| for (String sentence : sentences) { | ||
| String[] parts = sentence.split(" "); | ||
| for (String word : parts) { | ||
| words2.add(word); | ||
| } | ||
| } | ||
|
|
||
| // Найди самый дорогой продукт в каждой категории. | ||
| record Product(String name, String category, double price) {} | ||
| List<Product> products = List.of( | ||
| new Product("Phone", "Electronics", 1200), | ||
| new Product("TV", "Electronics", 1800), | ||
| new Product("Apple", "Fruits", 2.5), | ||
| new Product("Mango", "Fruits", 4.0)); | ||
|
|
||
| } | ||
| } | ||
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 |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| package streams; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class Streams { | ||
| public static void main(String[] args) { | ||
|
|
||
|
|
||
| // Дан список чисел. Оставь только чётные и выведи их квадраты. | ||
| // List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6); | ||
| List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6); | ||
| numbers.stream() | ||
| .filter(i -> i % 2 == 0) | ||
| .map(i -> i * i) | ||
| .toList(); | ||
|
|
||
|
|
||
| // Подсчитай, сколько строк в списке длиннее 5 символов. | ||
| List<String> words = List.of("apple", "banana", "pear", "pineapple"); | ||
| var count = words.stream() | ||
| .filter(s -> s.length() > 5) | ||
| .count(); | ||
|
|
||
| // Найди максимальное и минимальное число в списке с помощью Stream API. | ||
| List<Integer> nums = List.of(10, 2, 33, 4, 25); | ||
| var min = nums.stream() | ||
| .min(Comparator.naturalOrder()) | ||
| .orElseThrow(); | ||
|
|
||
| var max = nums.stream() | ||
| .max(Comparator.naturalOrder()) | ||
| .orElseThrow(); | ||
|
|
||
|
|
||
| // Посчитай среднюю длину строк в списке. | ||
| List<String> names = List.of("Alice", "Bob", "Charlie", "David"); | ||
| var avarage = names.stream() | ||
| .mapToInt(s -> s.length()) | ||
| .average(); | ||
|
|
||
|
|
||
| // Удали дубликаты и отсортируй строки по длине. | ||
| List<String> input = List.of("apple", "pear", "apple", "banana", "pear"); | ||
| var result = input.stream() | ||
| .distinct() | ||
| .sorted(Comparator.comparingInt(s -> s.length())) | ||
| .toList(); | ||
|
|
||
| // Преобразуй список строк в Map: ключ — строка, значение — длина. | ||
| List<String> fruits = List.of("apple", "banana", "kiwi"); | ||
| var newMap = fruits.stream() | ||
| .collect(Collectors.toMap(s -> s, s -> s.length())); | ||
|
|
||
| // Сгруппируй имена по первой букве. | ||
| List<String> names2 = List.of("Alice", "Andrew", "Bob", "Charlie", "Catherine"); | ||
|
|
||
| var grouped = names2.stream() | ||
| .collect(Collectors.groupingBy(s -> s.charAt(0))); | ||
|
|
||
| // Собери список имён в одну строку через запятую. | ||
| List<String> names3 = List.of("Tom", "Jerry", "Spike"); | ||
| var oneStringOfNames = names3.stream() | ||
| .collect(Collectors.joining(", ")); | ||
|
|
||
| // Из списка предложений получить список всех слов. | ||
| List<String> sentences = List.of("Java is cool", "Streams are powerful"); | ||
| var splitedToWords = sentences.stream() | ||
| .map(s -> s.split(" ")) // each sentence → array of words | ||
| .toList(); | ||
|
|
||
| var words2 = splitedToWords.stream() | ||
| .flatMap(Arrays::stream) // flatten each array into stream | ||
| .toList(); | ||
|
|
||
| // Найди самый дорогой продукт в каждой категории. | ||
| record Product(String name, String category, double price) {} | ||
| List<Product> products = List.of( | ||
| new Product("Phone", "Electronics", 1200), | ||
| new Product("TV", "Electronics", 1800), | ||
| new Product("Apple", "Fruits", 2.5), | ||
| new Product("Mango", "Fruits", 4.0)); | ||
|
|
||
| var mostExpensiveByCategory = products.stream() | ||
| .collect(Collectors.groupingBy( | ||
| Product::category, | ||
| Collectors.maxBy(Comparator.comparingDouble(Product::price)) | ||
| )); | ||
| } | ||
| } |
Empty file.
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.
надо использовать одинаковые типы данных
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.
работает autoboxing/unboxing