diff --git a/functional interface/functional interface.iml b/functional interface/functional interface.iml new file mode 100644 index 0000000..9465dd8 --- /dev/null +++ b/functional interface/functional interface.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/functional interface/out/production/functional interface/Main.class b/functional interface/out/production/functional interface/Main.class new file mode 100644 index 0000000..60bd177 Binary files /dev/null and b/functional interface/out/production/functional interface/Main.class differ diff --git a/functional interface/src/Main.java b/functional interface/src/Main.java new file mode 100644 index 0000000..b079615 --- /dev/null +++ b/functional interface/src/Main.java @@ -0,0 +1,92 @@ +//задания 1-10 + +import java.util.List; +import java.util.UUID; +import java.util.function.*; + +public class Main { + public static void main(String[] args) { +// Создай Predicate, который проверяет, что строка не пуста и длиннее 3 символов + Predicate threeORmore = s -> s != null && !s.isEmpty() && s.length() > 3; + + System.out.println(threeORmore.test("hi")); + System.out.println(threeORmore.test("")); + System.out.println(threeORmore.test("germany")); + System.out.println(threeORmore.test(null)); + +// Создай Function, возвращающую длину строки. + Function getLength = s -> s.length(); + + System.out.println(); + System.out.println("Germany is the country in my mind rigth now"); + System.out.println(getLength.apply("Germany is the country in my mind rigth now")); + +// Создай Supplier, который возвращает новый UUID при каждом вызове. + Supplier newUUID = () -> UUID.randomUUID(); + System.out.println("Тройка новых UUID"); + System.out.println(newUUID.get()); + System.out.println(newUUID.get()); + System.out.println(newUUID.get()); + +// Создай Consumer, который выводит строку в upper case. + Consumer toUpperTheString = s -> System.out.println(s.toUpperCase()); + + System.out.println("Строка для ввода"); + System.out.println("Some random sentence"); + toUpperTheString.accept("Some random sentence"); + +// Создай BiFunction, которая возвращает сумму двух чисел. + BiFunction sumoftwo = (a, b) -> a + b; + + System.out.println(sumoftwo.apply(6, 9)); + +// Function trim и Function toUpperCase. Объедини их в одну, которая сначала обрезает пробелы, потом делает верхний регистр + Function trim = s -> s.replaceAll(" ", ""); + Function toUppperCase = s -> s.toUpperCase(); + + Function trimandUpper = trim.andThen(toUppperCase); + + System.out.println(trimandUpper.apply("let you cut me open")); + +// Один Consumer печатает строку в консоль, второй — печатает длину строки. Объедини их через andThen(). +// печатание строки + Consumer printString = s -> System.out.println("Строка " + s); + +// печанание её длины + Consumer printLength = s -> System.out.println("Длина " + s.length()); + +// 2 в 1 + Consumer combination = printString.andThen(printLength); + + combination.accept("Osama bin Russel"); + +// Создай Predicate isEven и isPositive. Получи Predicate, который проверяет "нечётное или отрицательное". + Predicate isEven = n -> n % 2 == 0; + Predicate isPositive = n -> n > 0; + + Predicate oddORnegative = isEven.negate().or(isPositive.negate()); + + System.out.println(oddORnegative.test(15)); + System.out.println(oddORnegative.test(-69)); + System.out.println(oddORnegative.test(28)); + System.out.println(oddORnegative.test(0)); + +// BiFunction multiply = (a, b) -> a * b; Function toStr = x -> "Result: " + x; Используй andThen(), чтобы объединить в одну цепочку. + BiFunction multiply = (a, b) -> a * b; + Function toStr = x -> "Result " + x; + + BiFunction result = multiply.andThen(toStr); + + System.out.println(result.apply(6, 9)); + +// Создай UnaryOperator, который добавляет "!!!" к строке. + UnaryOperator addiction = s -> s.concat("!!!"); + System.out.println(addiction.apply("This is a warning like it or not")); + + + + + + + } +} \ No newline at end of file diff --git a/stream api/out/production/stream api/Main$1Product.class b/stream api/out/production/stream api/Main$1Product.class new file mode 100644 index 0000000..636874f Binary files /dev/null and b/stream api/out/production/stream api/Main$1Product.class differ diff --git a/stream api/out/production/stream api/Main.class b/stream api/out/production/stream api/Main.class new file mode 100644 index 0000000..b23a365 Binary files /dev/null and b/stream api/out/production/stream api/Main.class differ diff --git a/stream api/src/Main.java b/stream api/src/Main.java new file mode 100644 index 0000000..eef6ffd --- /dev/null +++ b/stream api/src/Main.java @@ -0,0 +1,136 @@ +import com.sun.jdi.Value; + +import java.security.Key; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Main { + public static void main(String[] args) { + + List numbers = List.of(1, 2, 3, 4, 5, 6); + System.out.println("\nКвадрат чётных цифр из 1-6"); + +// to double the values +// Stream doubledValues = numbers.stream().map(n -> n*2); + +// doubledValues.forEach(n -> System.out.println(n)); + +// to leave only odd ones and get their square values + numbers.stream() + .filter(n -> n%2 == 1) + .sorted() + .map(n -> n*n) + .forEach(n -> System.out.println(n)); + +// the number of words with length more than 5 + List words = List.of("apple", "banana", "pear", "pineapple"); + System.out.println("\nКоличество слов длиною больше 5"); + + + System.out.println(words.stream() + .filter(s -> s.length() > 5) +// .sorted() + .count()); +// .forEach(s -> System.out.println(s)); + +// max and min + List nums = List.of(10, 2, 33, 4, 25); + System.out.println("\nЛист из 10, 2, 33, 4, 25"); + nums.stream() + .min(Comparator.comparing(Integer::valueOf)) + .ifPresent(min -> System.out.println("Самое маленькое число:" + min)); + + nums.stream() + .max(Comparator.comparing(Integer::valueOf)) + .ifPresent(max -> System.out.println("Самый большой:" + max)); + +// средняя длина строк + List names = List.of("Alice", "Bob", "Charlie", "David"); + System.out.print("\nСредняя длина из 'Alice', 'Bob', 'Charlie' и 'David': "); + + double averageLength = names.stream() + .mapToInt(String::length) + .average() + .orElse(0); + + System.out.print(averageLength); + +// удаление дубликатов и отсортировка строки по длине + List fruits = List.of("apple", "pear", "apple", "banana", "kiwi"); + System.out.print("\nБыло \n" + + "'apple', 'pear', 'apple', 'banana', 'kiwi' \n" + + "Стало: "); + + List noduplicate = fruits.stream() + .distinct() + .sorted(Comparator.comparingInt(String::length)) + .collect(Collectors.toList()); + + System.out.print(noduplicate); + +// преобразование список в map + System.out.println("\nПреобразование List в Map "); + List fruits2 = List.of("apple", "banana", "kiwi"); + + Map fruits2Mapped = fruits2.stream() + .collect(Collectors.toMap( + fruit -> fruit, String::length + )); + + System.out.println( fruits2Mapped); + +// Map map = fruits2.stream().collect(Collectors.toMap(Item::getKey, item -> item)); +// +// map.forEach(k, v) ->System.out.println(k + " => " + v); + +// группировка имён по первой букве + List names2 = List.of("Alice", "Charlie", "Andrew", "Catherine", "Bob"); + System.out.println("Группировка \"Alice\", \"Charlie\", \"Andrew\", \"Catherine\", \"Bob\" по первой букве: "); + +String names2sorted = names2.stream() + .sorted() + .collect(Collectors.joining(", ")); + System.out.println(names2sorted); + +// собрать список имён в одну строку через запятую + List names3 = List.of("Tom", "Jerry", "Spike"); + + String oneLine = names3.stream() + .collect(Collectors.joining(", ")); + + System.out.println(oneLine); + +// Из списка предложений получить список всех слов. + List names4 = List.of("Java is cool", "Streams are powerful"); + + List names4Words = names4.stream() + .flatMap(sentence -> Arrays.stream(sentence.split(" "))) + .collect(Collectors.toList()); + System.out.println(names4Words); + +// Найди самый дорогой продукт в каждой категории. + record Product(String name, String category, double price){} + List 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)); + + Map mostExpensiveByCategory = products.stream() + .collect(Collectors.groupingBy( + Product::category, + Collectors.collectingAndThen( + Collectors.maxBy(Comparator.comparing(Product::price)), + Optional::get + ) + )); + + mostExpensiveByCategory.forEach((category, product) -> + System.out.println("Категория: " + category + + ", самый дорогой: " + product.name() + + " " + product.price())); + + } +} \ No newline at end of file diff --git a/stream api/stream api.iml b/stream api/stream api.iml new file mode 100644 index 0000000..9465dd8 --- /dev/null +++ b/stream api/stream api.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file