Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions functional interface/functional interface.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
Binary file not shown.
92 changes: 92 additions & 0 deletions functional interface/src/Main.java
Original file line number Diff line number Diff line change
@@ -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<String>, который проверяет, что строка не пуста и длиннее 3 символов
Predicate<String> 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<String, Integer>, возвращающую длину строки.
Function<String, Integer> 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>, который возвращает новый UUID при каждом вызове.
Supplier<UUID> newUUID = () -> UUID.randomUUID();
System.out.println("Тройка новых UUID");
System.out.println(newUUID.get());
System.out.println(newUUID.get());
System.out.println(newUUID.get());

// Создай Consumer<String>, который выводит строку в upper case.
Consumer<String> toUpperTheString = s -> System.out.println(s.toUpperCase());

System.out.println("Строка для ввода");
System.out.println("Some random sentence");
toUpperTheString.accept("Some random sentence");

// Создай BiFunction<Integer, Integer, Integer>, которая возвращает сумму двух чисел.
BiFunction<Integer, Integer, Integer> sumoftwo = (a, b) -> a + b;

System.out.println(sumoftwo.apply(6, 9));

// Function<String, String> trim и Function<String, String> toUpperCase. Объедини их в одну, которая сначала обрезает пробелы, потом делает верхний регистр
Function<String, String> trim = s -> s.replaceAll(" ", "");
Function<String, String> toUppperCase = s -> s.toUpperCase();

Function<String, String> trimandUpper = trim.andThen(toUppperCase);

System.out.println(trimandUpper.apply("let you cut me open"));

// Один Consumer печатает строку в консоль, второй — печатает длину строки. Объедини их через andThen().
// печатание строки
Consumer<String> printString = s -> System.out.println("Строка " + s);

// печанание её длины
Consumer<String> printLength = s -> System.out.println("Длина " + s.length());

// 2 в 1
Consumer<String> combination = printString.andThen(printLength);

combination.accept("Osama bin Russel");

// Создай Predicate<Integer> isEven и isPositive. Получи Predicate, который проверяет "нечётное или отрицательное".
Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isPositive = n -> n > 0;

Predicate<Integer> 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<Integer, Integer, Integer> multiply = (a, b) -> a * b; Function<Integer, String> toStr = x -> "Result: " + x; Используй andThen(), чтобы объединить в одну цепочку.
BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b;
Function<Integer, String> toStr = x -> "Result " + x;

BiFunction<Integer, Integer, String> result = multiply.andThen(toStr);

System.out.println(result.apply(6, 9));

// Создай UnaryOperator<String>, который добавляет "!!!" к строке.
UnaryOperator<String> addiction = s -> s.concat("!!!");
System.out.println(addiction.apply("This is a warning like it or not"));






}
}
Binary file not shown.
Binary file added stream api/out/production/stream api/Main.class
Binary file not shown.
136 changes: 136 additions & 0 deletions stream api/src/Main.java
Original file line number Diff line number Diff line change
@@ -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<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
System.out.println("\nКвадрат чётных цифр из 1-6");

// to double the values
// Stream<Integer> 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<String> 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<Integer> 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 <String> 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<String> fruits = List.of("apple", "pear", "apple", "banana", "kiwi");
System.out.print("\nБыло \n" +
"'apple', 'pear', 'apple', 'banana', 'kiwi' \n" +
"Стало: ");

List<String> noduplicate = fruits.stream()
.distinct()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());

System.out.print(noduplicate);

// преобразование список в map
System.out.println("\nПреобразование List в Map ");
List<String> fruits2 = List.of("apple", "banana", "kiwi");

Map<String, Integer> fruits2Mapped = fruits2.stream()
.collect(Collectors.toMap(
fruit -> fruit, String::length
));

System.out.println( fruits2Mapped);

// Map<String, Item> map = fruits2.stream().collect(Collectors.toMap(Item::getKey, item -> item));
//
// map.forEach(k, v) ->System.out.println(k + " => " + v);

// группировка имён по первой букве
List<String> 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<String> names3 = List.of("Tom", "Jerry", "Spike");

String oneLine = names3.stream()
.collect(Collectors.joining(", "));

System.out.println(oneLine);

// Из списка предложений получить список всех слов.
List<String> names4 = List.of("Java is cool", "Streams are powerful");

List<String> 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<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));

Map<String, Product> 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()));

}
}
11 changes: 11 additions & 0 deletions stream api/stream api.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>