diff --git a/lessons/.gradle/8.13/executionHistory/executionHistory.bin b/lessons/.gradle/8.13/executionHistory/executionHistory.bin index 89c5370..492a31e 100644 Binary files a/lessons/.gradle/8.13/executionHistory/executionHistory.bin and b/lessons/.gradle/8.13/executionHistory/executionHistory.bin differ diff --git a/lessons/.gradle/8.13/executionHistory/executionHistory.lock b/lessons/.gradle/8.13/executionHistory/executionHistory.lock index 76f66aa..9ed029f 100644 Binary files a/lessons/.gradle/8.13/executionHistory/executionHistory.lock and b/lessons/.gradle/8.13/executionHistory/executionHistory.lock differ diff --git a/lessons/.gradle/8.13/fileHashes/fileHashes.bin b/lessons/.gradle/8.13/fileHashes/fileHashes.bin index 9f95a89..cf08a0f 100644 Binary files a/lessons/.gradle/8.13/fileHashes/fileHashes.bin and b/lessons/.gradle/8.13/fileHashes/fileHashes.bin differ diff --git a/lessons/.gradle/8.13/fileHashes/fileHashes.lock b/lessons/.gradle/8.13/fileHashes/fileHashes.lock index 0ef8a01..1b37c97 100644 Binary files a/lessons/.gradle/8.13/fileHashes/fileHashes.lock and b/lessons/.gradle/8.13/fileHashes/fileHashes.lock differ diff --git a/lessons/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/lessons/.gradle/buildOutputCleanup/buildOutputCleanup.lock index 00e9ec4..9684afd 100644 Binary files a/lessons/.gradle/buildOutputCleanup/buildOutputCleanup.lock and b/lessons/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/lessons/.gradle/buildOutputCleanup/outputFiles.bin b/lessons/.gradle/buildOutputCleanup/outputFiles.bin index a6faea7..677178f 100644 Binary files a/lessons/.gradle/buildOutputCleanup/outputFiles.bin and b/lessons/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/lessons/.gradle/file-system.probe b/lessons/.gradle/file-system.probe index f55ab29..d8f6ea8 100644 Binary files a/lessons/.gradle/file-system.probe and b/lessons/.gradle/file-system.probe differ diff --git a/lessons/src/main/java/lesson12/FunctionalInterface.java b/lessons/src/main/java/lesson12/FunctionalInterface.java new file mode 100644 index 0000000..efc80f2 --- /dev/null +++ b/lessons/src/main/java/lesson12/FunctionalInterface.java @@ -0,0 +1,218 @@ +package lesson12; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.function.*; + +/** + * @author Shohjahon + * @version 1 + */ + +public class FunctionalInterface { + public static void main(String[] args) { + //ManualGenerate(); + //ManualForEach(); + //ManualMap(); + //ManualFilter(); + //UnaryOperator(); + //BiFunctionAndThen(); + //Predicate(); + //ConsumerAndThen(); + //FunctionCombine(); + //SumBiFunction(); + //UpperCaseConsumer(); + //UUIDSupplier(); + //StringLength(); + //StringPredicate(); + } + + private static void ManualGenerate() { + Supplier randomIntSupplier = () -> (int) (Math.random() * 100); + + List randomNumbers = generate(randomIntSupplier, 5); + + System.out.println(randomNumbers); + + Supplier uuidSupplier = () -> UUID.randomUUID().toString(); + List uuids = generate(uuidSupplier, 3); + uuids.forEach(System.out::println); + } + + public static List generate(Supplier supplier, int n) { + List result = new ArrayList<>(); + for (int i = 0; i < n; i++) { + result.add(supplier.get()); + } + return result; + } + + private static void ManualForEach() { + List words = List.of("apple", "pear", "banana", "kiwi"); + + Consumer print = System.out::println; + + forEach(words, print); + } + + public static void forEach(List list, Consumer consumer) { + for (T element : list) { + consumer.accept(element); + } + } + + private static void ManualMap() { + List words = List.of("apple", "pear", "banana", "kiwi"); + + Function stringLength = String::length; + + List lengths = map(words, stringLength); + + System.out.println(lengths); + } + + public static List map(List list, Function mapper) { + List result = new ArrayList<>(); + for (T element : list) { + result.add(mapper.apply(element)); + } + return result; + } + + private static void ManualFilter() { + List words = List.of("apple", "pear", "banana", "kiwi"); + + Predicate longerThanFour = s -> s.length() > 4; + + List filteredWords = filter(words, longerThanFour); + + System.out.println(filteredWords); + } + + public static List filter(List list, Predicate predicate) { + List result = new ArrayList<>(); + for (T element : list) { + if (predicate.test(element)) { + result.add(element); + } + } + return result; + } + + private static void UnaryOperator() { + UnaryOperator addExclamations = s -> s + "!!!"; + + String[] testStrings = {"Hello", "Java", "Shohjahon"}; + + for (String str : testStrings) { + System.out.println(addExclamations.apply(str)); + } + } + + private static void BiFunctionAndThen() { + BiFunction multiply = (a, b) -> a * b; + + Function toStr = x -> "Result: " + x; + + Function multiplyThenToStr = arr -> toStr.apply(multiply.apply(arr[0], arr[1])); + + int a = 5, b = 3; + System.out.println(multiplyThenToStr.apply(new Integer[]{a, b})); + + a = 7; + b = 4; + System.out.println(multiplyThenToStr.apply(new Integer[]{a, b})); + } + + private static void Predicate() { + Predicate isEven = n -> n % 2 == 0; + + Predicate isPositive = n -> n > 0; + + Predicate evenAndPositive = isEven.and(isPositive); + + Predicate oddOrNegative = evenAndPositive.negate(); + + int[] numbers = {-3, -2, 0, 1, 2, 3, 4}; + + for (int n : numbers) { + System.out.println(n + " -> evenAndPositive: " + evenAndPositive.test(n) + + ", oddOrNegative: " + oddOrNegative.test(n)); + } + } + + private static void ConsumerAndThen() { + Consumer printString = s -> System.out.println("String: " + s); + + Consumer printLength = s -> System.out.println("Length: " + s.length()); + + Consumer combined = printString.andThen(printLength); + + String[] testStrings = {"Hello", "Java", "Shohjahon"}; + + for (String str : testStrings) { + combined.accept(str); + } + } + + private static void FunctionCombine() { + Function trim = String::trim; + + Function toUpperCase = String::toUpperCase; + + Function trimThenUpper = trim.andThen(toUpperCase); + + String[] testStrings = {" hello ", " Java ", " Shohjahon "}; + + for (String str : testStrings) { + System.out.println("'" + trimThenUpper.apply(str) + "'"); + } + } + + private static void SumBiFunction() { + BiFunction sum = Integer::sum; + + System.out.println("5 + 3 = " + sum.apply(5, 3)); + System.out.println("10 + 20 = " + sum.apply(10, 20)); + System.out.println("-2 + 7 = " + sum.apply(-2, 7)); + } + + private static void UpperCaseConsumer() { + Consumer printUpperCase = s -> System.out.println(s.toUpperCase()); + + String[] testStrings = {"hello", "java", "shohjahon"}; + + for (String str : testStrings) { + printUpperCase.accept(str); + } + } + + private static void UUIDSupplier() { + Supplier uuidSupplier = UUID::randomUUID; + + for (int i = 0; i < 3; i++) { + System.out.println(uuidSupplier.get()); + } + } + + private static void StringLength() { + Function stringLength = String::length; + + String[] testStrings = {"Hello", "Java", "Shohjahon", ""}; + + for (String str : testStrings) { + System.out.println(str + " -> " + stringLength.apply(str)); + } + } + + private static void StringPredicate() { + Predicate isValid = s -> s.length() > 3; + + String[] testStrings = {"", "Hi", "Java", "Shohjahon"}; + + for (String str : testStrings) { + System.out.println(str + " -> " + isValid.test(str)); + } + } +} diff --git a/lessons/src/main/java/lesson12/streamapi/Product.java b/lessons/src/main/java/lesson12/streamapi/Product.java new file mode 100644 index 0000000..9b565bd --- /dev/null +++ b/lessons/src/main/java/lesson12/streamapi/Product.java @@ -0,0 +1,4 @@ +package lesson12.streamapi; + +public record Product(String name, String category, double price) { +} diff --git a/lessons/src/main/java/lesson12/streamapi/WithFor.java b/lessons/src/main/java/lesson12/streamapi/WithFor.java new file mode 100644 index 0000000..56dcf2d --- /dev/null +++ b/lessons/src/main/java/lesson12/streamapi/WithFor.java @@ -0,0 +1,180 @@ +package lesson12.streamapi; + +import java.util.*; + +/** + * @author Shohjahon + * @version 1 + */ + +public class WithFor { + public static void main(String[] args) { + //EvenSquares(); + //CountLongWords(); + //FindMinMax(); + //AverageStringLength(); + //RemoveDuplicatesAndSort(); + //ToMap(); + //GroupByFirstLetter(); + //JoinNames(); + //SplitSentences(); + //MostExpensive(); + } + + private static void MostExpensive() { + 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 mostExpensive = new HashMap<>(); + + for (Product p : products) { + if (!mostExpensive.containsKey(p.category()) || + p.price() > mostExpensive.get(p.category()).price()) { + mostExpensive.put(p.category(), p); + } + } + + for (String category : mostExpensive.keySet()) { + Product product = mostExpensive.get(category); + System.out.println(category + " -> " + product.name() + " ($" + product.price() + ")"); + } + } + + private static void SplitSentences() { + List sentences = List.of("Java is cool", "Streams are powerful"); + + List words = new ArrayList<>(); + + for (String sentence : sentences) { + String[] splitWords = sentence.split(" "); + words.addAll(Arrays.asList(splitWords)); + } + + System.out.println(words); + } + + private static void JoinNames() { + List names = List.of("Tom", "Jerry", "Spike"); + + StringBuilder result = new StringBuilder(); + for (int i = 0; i < names.size(); i++) { + result.append(names.get(i)); + if (i < names.size() - 1) { + result.append(", "); + } + } + + System.out.println(result); + } + + private static void GroupByFirstLetter() { + List names = List.of("Alice", "Andrew", "Bob", "Charlie", "Catherine"); + + Map> grouped = new HashMap<>(); + + for (String name : names) { + char firstLetter = name.charAt(0); + + if (!grouped.containsKey(firstLetter)) { + grouped.put(firstLetter, new ArrayList<>()); + } + + grouped.get(firstLetter).add(name); + } + + System.out.println(grouped); + } + + private static void ToMap() { + List fruits = List.of("apple", "banana", "kiwi"); + + Map fruitMap = new HashMap<>(); + + for (String fruit : fruits) { + fruitMap.put(fruit, fruit.length()); + } + + System.out.println(fruitMap); + } + + private static void RemoveDuplicatesAndSort() { + List input = List.of("apple", "pear", "apple", "banana", "pear"); + + Set uniqueSet = new HashSet<>(input); + + List uniqueList = new ArrayList<>(uniqueSet); + + for (int i = 0; i < uniqueList.size() - 1; i++) { + for (int j = i + 1; j < uniqueList.size(); j++) { + if (uniqueList.get(i).length() > uniqueList.get(j).length()) { + String temp = uniqueList.get(i); + uniqueList.set(i, uniqueList.get(j)); + uniqueList.set(j, temp); + } + } + } + + System.out.println("Result: " + uniqueList); + } + + private static void AverageStringLength() { + List names = List.of("Alice", "Bob", "Charlie", "David"); + + int totalLength = 0; + + for (String name : names) { + totalLength += name.length(); + } + + double average = (double) totalLength / names.size(); + + System.out.println("Average length: " + average); + } + + private static void FindMinMax() { + List nums = List.of(10, 2, 33, 4, 25); + + int max = nums.getFirst(); + int min = nums.getFirst(); + + for (int num : nums) { + if (num > max) { + max = num; + } + if (num < min) { + min = num; + } + } + + System.out.println("Maximum: " + max); + System.out.println("Minimum: " + min); + } + + private static void CountLongWords() { + List words = List.of("apple", "banana", "pear", "pineapple"); + + int count = 0; + for (String word : words) { + if (word.length() > 5) { + count++; + } + } + + System.out.printf("Number of words longer than 5 characters: %s.", count); + } + + private static void EvenSquares() { + List numbers = List.of(1, 2, 3, 4, 5, 6); + + for (int number : numbers) { + if (number % 2 == 0) { + int square = number * number; + System.out.println(square); + } + } + } +} diff --git a/lessons/src/main/java/lesson12/streamapi/WithStream.java b/lessons/src/main/java/lesson12/streamapi/WithStream.java new file mode 100644 index 0000000..8646ffb --- /dev/null +++ b/lessons/src/main/java/lesson12/streamapi/WithStream.java @@ -0,0 +1,140 @@ +package lesson12.streamapi; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @author Shohjahon + * @version 1 + */ + +public class WithStream { + public static void main(String[] args) { + //MostExpensive(); + //WordsFromSentences(); + //JoinNames(); + //GroupByFirstLetter(); + //ListToMap(); + //RemoveDuplicatesAndSort(); + //AverageStringLength(); + //MinMax(); + //CountLongWords(); + //EvenSquares(); + } + + private static void MostExpensive() { + 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> mostExpensive = products.stream() + .collect(Collectors.groupingBy( + Product::category, + Collectors.maxBy(Comparator.comparingDouble(Product::price)) + )); + + mostExpensive.forEach((category, productOpt) -> + productOpt.ifPresent(product -> + System.out.println(category + " -> " + product.name() + " ($" + product.price() + ")") + ) + ); + } + + private static void WordsFromSentences() { + List sentences = List.of("Java is cool", "Streams are powerful"); + + List words = sentences.stream() + .flatMap(sentence -> Stream.of(sentence.split(" "))) + .collect(Collectors.toList()); + + System.out.println(words); + } + + private static void JoinNames() { + List names = List.of("Tom", "Jerry", "Spike"); + + String result = names.stream() + .collect(Collectors.joining(", ")); + + System.out.println(result); + } + + private static void GroupByFirstLetter() { + List names = List.of("Alice", "Andrew", "Bob", "Charlie", "Catherine"); + + Map> grouped = names.stream() + .collect(Collectors.groupingBy(name -> name.charAt(0))); + + System.out.println(grouped); + } + + private static void ListToMap() { + List fruits = List.of("apple", "banana", "kiwi"); + + Map fruitLengthMap = fruits.stream() + .collect(Collectors.toMap( + fruit -> fruit, + String::length + )); + + System.out.println(fruitLengthMap); + } + + private static void RemoveDuplicatesAndSort() { + List input = List.of("apple", "pear", "apple", "banana", "pear"); + + List result = input.stream() + .distinct() + .sorted(Comparator.comparingInt(String::length)) + .collect(Collectors.toList()); + + System.out.println(result); + } + + private static void AverageStringLength() { + List names = List.of("Alice", "Bob", "Charlie", "David"); + + double average = names.stream() + .mapToInt(String::length) + .average() + .orElse(0); + + System.out.println("Average length: " + average); + } + + private static void MinMax() { + List nums = List.of(10, 2, 33, 4, 25); + + Optional max = nums.stream().max(Integer::compareTo); + Optional min = nums.stream().min(Integer::compareTo); + + max.ifPresent(m -> System.out.println("Maximum: " + m)); + min.ifPresent(m -> System.out.println("Minimum: " + m)); + } + + private static void CountLongWords() { + List words = List.of("apple", "banana", "pear", "pineapple"); + + long count = words.stream() + .filter(word -> word.length() > 5) + .count(); + + System.out.println("Number of words longer than 5 characters: " + count); + } + + private static void EvenSquares() { + List numbers = List.of(1, 2, 3, 4, 5, 6); + + numbers.stream() + .filter(n -> n % 2 == 0) + .map(n -> n * n) + .forEach(System.out::println); + } +} diff --git a/lessons/src/main/java/lessons/lesson01/Main.java b/lessons/src/main/java/lessons/lesson01/Main.java deleted file mode 100644 index c725125..0000000 --- a/lessons/src/main/java/lessons/lesson01/Main.java +++ /dev/null @@ -1,15 +0,0 @@ -package lessons.lesson01; - -public class Main { - - int value = 5; - String name = "Mike"; - - static final int DEFAULT_VALUE = 0; - static final String DEFAULT_NAME = "John"; -// test - public static void main(String[] args) { - System.out.println("Hello, World!"); - Math.abs(1); - } -} \ No newline at end of file