|
| 1 | +package com.bobocode; |
| 2 | + |
| 3 | +import com.bobocode.data.Accounts; |
| 4 | +import com.bobocode.model.Account; |
| 5 | + |
| 6 | +import java.util.Random; |
| 7 | +import java.util.function.Consumer; |
| 8 | +import java.util.function.Function; |
| 9 | +import java.util.function.Predicate; |
| 10 | +import java.util.function.Supplier; |
| 11 | +import java.util.stream.IntStream; |
| 12 | + |
| 13 | +/** |
| 14 | + * A list of predefined interfaces examples. |
| 15 | + */ |
| 16 | +public class PredefinedInterfacesExamples { |
| 17 | + public static void main(String[] args) { |
| 18 | + |
| 19 | + printEmailUsingAccountConsumer(); |
| 20 | + |
| 21 | + printARandomNumberUsingIntegerSupplier(); |
| 22 | + |
| 23 | + calculate3xValueUsingIntegerFunction(); |
| 24 | + |
| 25 | + checkIfNumberIsPositiveUsingIntegerPredicate(); |
| 26 | + |
| 27 | + verifyGoogleEmailUsingAccountPredicate(); |
| 28 | + |
| 29 | + printPrimeNumbersUsingIntegerPredicate(); |
| 30 | + |
| 31 | + } |
| 32 | + |
| 33 | + private static void printARandomNumberUsingIntegerSupplier() { |
| 34 | + Supplier<Integer> integerSupplier = () -> new Random().nextInt(1000); |
| 35 | + |
| 36 | + System.out.println("Next value: " + integerSupplier.get()); |
| 37 | + } |
| 38 | + |
| 39 | + private static void printEmailUsingAccountConsumer() { |
| 40 | + Consumer<Account> accountConsumer = acc -> System.out.println(acc.getEmail()); |
| 41 | + Account account = Accounts.getAccount(); |
| 42 | + |
| 43 | + accountConsumer.accept(account); |
| 44 | + } |
| 45 | + |
| 46 | + private static void calculate3xValueUsingIntegerFunction() { |
| 47 | + Function<Integer, Integer> tripleFunction = n -> 3 * n; |
| 48 | + int a = 12; |
| 49 | + |
| 50 | + System.out.println("3 * " + a + tripleFunction.apply(a)); |
| 51 | + } |
| 52 | + |
| 53 | + private static void checkIfNumberIsPositiveUsingIntegerPredicate() { |
| 54 | + Predicate<Integer> isPositive = n -> n > 0; |
| 55 | + int b = 23; |
| 56 | + |
| 57 | + System.out.println(b + " is " + (isPositive.test(b) ? "positive" : "negative")); |
| 58 | + } |
| 59 | + |
| 60 | + private static void verifyGoogleEmailUsingAccountPredicate() { |
| 61 | + Account account = Accounts.getAccount(); |
| 62 | + Predicate<Account> isGmailUser = a -> a.getEmail().endsWith("@gmail.com"); |
| 63 | + |
| 64 | + System.out.println("\"" + account.getEmail() + "\"" + " is " |
| 65 | + + (isGmailUser.test(account) ? "" : "not") + " a Google mail."); |
| 66 | + } |
| 67 | + |
| 68 | + private static void printPrimeNumbersUsingIntegerPredicate() { |
| 69 | + Predicate<Integer> isPrime = n -> IntStream.range(2, n).noneMatch(i -> n % i == 0); |
| 70 | + |
| 71 | + IntStream.range(1, 10) |
| 72 | + .forEach(i -> System.out.printf("%3d %10s\n", i, (isPrime.test(i) ? " is prime" : ""))); |
| 73 | + } |
| 74 | +} |
0 commit comments