diff --git a/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java b/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java index d5398ab..4253cf9 100644 --- a/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java +++ b/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.util.Map; +import java.util.Random; import java.util.function.*; public class CrazyLambdas { @@ -12,7 +13,8 @@ public class CrazyLambdas { * @return a string supplier */ public static Supplier helloSupplier() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return () -> "Hello"; } /** @@ -21,7 +23,8 @@ public static Supplier helloSupplier() { * @return a string predicate */ public static Predicate isEmptyPredicate() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return String::isEmpty; } /** @@ -31,7 +34,8 @@ public static Predicate isEmptyPredicate() { * @return function that repeats Strings */ public static BiFunction stringMultiplier() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return String::repeat; } /** @@ -41,7 +45,8 @@ public static BiFunction stringMultiplier() { * @return function that converts adds dollar sign */ public static Function toDollarStringFunction() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return bigDecimal -> "$" + bigDecimal.toString(); } /** @@ -53,7 +58,8 @@ public static Function toDollarStringFunction() { * @return a string predicate */ public static Predicate lengthInRangePredicate(int min, int max) { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return s -> s.length() >= min && s.length() < max; } /** @@ -62,7 +68,8 @@ public static Predicate lengthInRangePredicate(int min, int max) { * @return int supplier */ public static IntSupplier randomIntSupplier() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return () -> new Random().nextInt(); } @@ -72,7 +79,8 @@ public static IntSupplier randomIntSupplier() { * @return int operation */ public static IntUnaryOperator boundedRandomIntSupplier() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return operand -> new Random(operand).nextInt(); } /** @@ -81,7 +89,8 @@ public static IntUnaryOperator boundedRandomIntSupplier() { * @return square operation */ public static IntUnaryOperator intSquareOperation() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return operand -> operand * operand; } /** @@ -90,7 +99,8 @@ public static IntUnaryOperator intSquareOperation() { * @return binary sum operation */ public static LongBinaryOperator longSumOperation() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return Long::sum; } /** @@ -99,7 +109,8 @@ public static LongBinaryOperator longSumOperation() { * @return string to int converter */ public static ToIntFunction stringToIntConverter() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return Integer::parseInt; } /** @@ -110,7 +121,8 @@ public static ToIntFunction stringToIntConverter() { * @return a function supplier */ public static Supplier nMultiplyFunctionSupplier(int n) { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return () -> operand -> operand * n; } /** @@ -119,7 +131,8 @@ public static Supplier nMultiplyFunctionSupplier(int n) { * @return function that composes functions with trim() function */ public static UnaryOperator> composeWithTrimFunction() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return function -> function.compose(String::trim); } /** @@ -130,7 +143,12 @@ public static UnaryOperator> composeWithTrimFunction() * @return a thread supplier */ public static Supplier runningThreadSupplier(Runnable runnable) { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return () -> { + Thread thread = new Thread(runnable); + thread.start(); + return thread; + }; } /** @@ -139,7 +157,8 @@ public static Supplier runningThreadSupplier(Runnable runnable) { * @return a runnable consumer */ public static Consumer newThreadRunnableConsumer() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return Runnable::run; } /** @@ -149,7 +168,12 @@ public static Consumer newThreadRunnableConsumer() { * @return a function that transforms runnable into a thread supplier */ public static Function> runnableToThreadSupplierFunction() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return function -> () -> { + Thread thread = new Thread(function); + thread.start(); + return thread; + }; } /** @@ -162,7 +186,9 @@ public static Function> runnableToThreadSupplierFunct * @return a binary function that receiver predicate and function and compose them to create a new function */ public static BiFunction functionToConditionalFunction() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return (intUnaryOperator, intPredicate) -> + intUnaryOperator.compose(i -> intPredicate.test(i) ? i : intUnaryOperator.applyAsInt(i)); } /** @@ -173,7 +199,8 @@ public static BiFunction funct * @return a high-order function that fetches a function from a function map by a given name or returns identity() */ public static BiFunction, String, IntUnaryOperator> functionLoader() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return (map, s) -> map.getOrDefault(s, IntUnaryOperator.identity()); } /** @@ -182,7 +209,8 @@ public static BiFunction, String, IntUnaryOperator * @return a supplier instance */ public static Supplier>> trickyWellDoneSupplier() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return () -> () -> () -> "WELL DONE!"; } } diff --git a/crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java b/crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java index d81fe02..521a103 100644 --- a/crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java +++ b/crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java @@ -11,9 +11,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.math.BigDecimal; -import java.util.List; -import java.util.Optional; -import java.util.OptionalDouble; +import java.util.*; public class CrazyOptionals { @@ -24,7 +22,8 @@ public class CrazyOptionals { * @return optional object that holds text */ public static Optional optionalOfString(@Nullable String text) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return Optional.ofNullable(text); } /** @@ -34,7 +33,9 @@ public static Optional optionalOfString(@Nullable String text) { * @param amount money to deposit */ public static void deposit(AccountProvider accountProvider, BigDecimal amount) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + accountProvider.getAccount(). + ifPresent(account -> account.setBalance(account.getBalance().add(amount))); } /** @@ -44,7 +45,8 @@ public static void deposit(AccountProvider accountProvider, BigDecimal amount) { * @return optional object that holds account */ public static Optional optionalOfAccount(@Nonnull Account account) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return Optional.of(account); } /** @@ -56,7 +58,9 @@ public static Optional optionalOfAccount(@Nonnull Account account) { * @return account from provider or defaultAccount */ public static Account getAccount(AccountProvider accountProvider, Account defaultAccount) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accountProvider.getAccount() + .orElse(defaultAccount); } /** @@ -67,7 +71,9 @@ public static Account getAccount(AccountProvider accountProvider, Account defaul * @param accountService */ public static void processAccount(AccountProvider accountProvider, AccountService accountService) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + accountProvider.getAccount() + .ifPresentOrElse(accountService::processAccount, accountService::processWithNoAccount); } /** @@ -78,7 +84,10 @@ public static void processAccount(AccountProvider accountProvider, AccountServic * @return provided or generated account */ public static Account getOrGenerateAccount(AccountProvider accountProvider) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done +// return accountProvider.getAccount().orElse(Accounts.generateAccount()); + return accountProvider.getAccount() + .orElseGet(Accounts::generateAccount); } /** @@ -88,7 +97,9 @@ public static Account getOrGenerateAccount(AccountProvider accountProvider) { * @return optional balance */ public static Optional retrieveBalance(AccountProvider accountProvider) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accountProvider.getAccount() + .map(Account::getBalance); } /** @@ -99,7 +110,9 @@ public static Optional retrieveBalance(AccountProvider accountProvid * @return provided account */ public static Account getAccount(AccountProvider accountProvider) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accountProvider.getAccount() + .orElseThrow(() -> new AccountNotFoundException("No Account provided!")); } /** @@ -109,7 +122,9 @@ public static Account getAccount(AccountProvider accountProvider) { * @return optional credit balance */ public static Optional retrieveCreditBalance(CreditAccountProvider accountProvider) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accountProvider.getAccount() + .flatMap(CreditAccount::getCreditBalance); } @@ -121,7 +136,11 @@ public static Optional retrieveCreditBalance(CreditAccountProvider a * @return optional gmail account */ public static Optional retrieveAccountGmail(AccountProvider accountProvider) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accountProvider.getAccount() + .filter(account -> account.getEmail().split("@")[1].equals("gmail.com")) +// .or(Optional::empty) + ; } /** @@ -134,7 +153,10 @@ public static Optional retrieveAccountGmail(AccountProvider accountProv * @return account got from either accountProvider or fallbackProvider */ public static Account getAccountWithFallback(AccountProvider accountProvider, AccountProvider fallbackProvider) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accountProvider.getAccount() + .or(fallbackProvider::getAccount) + .orElseThrow(); } /** @@ -145,7 +167,10 @@ public static Account getAccountWithFallback(AccountProvider accountProvider, Ac * @return account with the highest balance */ public static Account getAccountWithMaxBalance(List accounts) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accounts.stream() + .max(Comparator.comparing(Account::getBalance)) + .orElseThrow(NoSuchElementException::new); } /** @@ -155,7 +180,11 @@ public static Account getAccountWithMaxBalance(List accounts) { * @return the lowest balance values */ public static OptionalDouble findMinBalanceValue(List accounts) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accounts.stream() + .map(Account::getBalance) + .mapToDouble(BigDecimal::doubleValue) + .min(); } /** @@ -165,7 +194,13 @@ public static OptionalDouble findMinBalanceValue(List accounts) { * @param accountService */ public static void processAccountWithMaxBalance(List accounts, AccountService accountService) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done +// accountService.processAccount(accounts.stream() +// .max(Comparator.comparing(Account::getBalance)) +// .get()); + accounts.stream() + .max(Comparator.comparing(Account::getBalance)) + .ifPresent(accountService::processAccount); } /** @@ -175,7 +210,12 @@ public static void processAccountWithMaxBalance(List accounts, AccountS * @return total credit balance */ public static double calculateTotalCreditBalance(List accounts) { - throw new UnsupportedOperationException("Some people say that method does not work until you implement it"); + // todo: done + return accounts.stream() + .map(CreditAccount::getCreditBalance) + .flatMap(Optional::stream) + .mapToDouble(BigDecimal::doubleValue) + .sum(); } } diff --git a/crazy-optionals/src/test/java/com/CrazyOptionalsTest.java b/crazy-optionals/src/test/java/com/bobocode/CrazyOptionalsTest.java similarity index 99% rename from crazy-optionals/src/test/java/com/CrazyOptionalsTest.java rename to crazy-optionals/src/test/java/com/bobocode/CrazyOptionalsTest.java index d36669e..e601711 100644 --- a/crazy-optionals/src/test/java/com/CrazyOptionalsTest.java +++ b/crazy-optionals/src/test/java/com/bobocode/CrazyOptionalsTest.java @@ -1,4 +1,4 @@ -package com; +package com.bobocode; import com.bobocode.CrazyOptionals; diff --git a/crazy-streams/src/main/java/com.bobocode/CrazyStreams.java b/crazy-streams/src/main/java/com.bobocode/CrazyStreams.java index 268ea0a..6581167 100644 --- a/crazy-streams/src/main/java/com.bobocode/CrazyStreams.java +++ b/crazy-streams/src/main/java/com.bobocode/CrazyStreams.java @@ -2,14 +2,15 @@ import com.bobocode.exception.EntityNotFoundException; import com.bobocode.model.Account; +import com.bobocode.model.Sex; import java.math.BigDecimal; import java.time.Month; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; +import java.util.*; + +import static java.util.Comparator.comparing; +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.*; /** * Implement methods using Stream API @@ -31,7 +32,9 @@ private CrazyStreams(Collection accounts) { * @return account with max balance wrapped with optional */ public Optional findRichestPerson() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .max(comparing(Account::getBalance)); } /** @@ -41,7 +44,10 @@ public Optional findRichestPerson() { * @return a list of accounts */ public List findAccountsByBirthdayMonth(Month birthdayMonth) { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .filter(account -> account.getBirthday().getMonth().equals(birthdayMonth)) + .collect(toList()); } /** @@ -51,7 +57,10 @@ public List findAccountsByBirthdayMonth(Month birthdayMonth) { * @return a map where key is true or false, and value is list of male, and female accounts */ public Map> partitionMaleAccounts() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .collect(groupingBy(account -> account.getSex().equals(Sex.MALE))); +// .collect(Collectors.partitioningBy(account -> account.getSex().equals(Sex.MALE))); } /** @@ -61,7 +70,9 @@ public Map> partitionMaleAccounts() { * @return a map where key is an email domain and value is a list of all account with such email */ public Map> groupAccountsByEmailDomain() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .collect(groupingBy(account -> account.getEmail().split("@")[1])); } /** @@ -70,7 +81,10 @@ public Map> groupAccountsByEmailDomain() { * @return total number of letters of first and last names of all accounts */ public int getNumOfLettersInFirstAndLastNames() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .mapToInt(value -> value.getFirstName().length() + value.getLastName().length()) + .sum(); } /** @@ -79,7 +93,10 @@ public int getNumOfLettersInFirstAndLastNames() { * @return total balance of all accounts */ public BigDecimal calculateTotalBalance() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .map(Account::getBalance) + .reduce(BigDecimal.ZERO, BigDecimal::add); } /** @@ -88,7 +105,10 @@ public BigDecimal calculateTotalBalance() { * @return list of accounts sorted by first and last names */ public List sortByFirstAndLastNames() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .sorted(comparing(Account::getFirstName).thenComparing(Account::getLastName)) + .collect(toList()); } /** @@ -98,7 +118,9 @@ public List sortByFirstAndLastNames() { * @return true if there is an account that has an email with provided domain */ public boolean containsAccountWithEmailDomain(String emailDomain) { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .anyMatch(account -> account.getEmail().split("@")[1].equals(emailDomain)); } /** @@ -109,7 +131,12 @@ public boolean containsAccountWithEmailDomain(String emailDomain) { * @return account balance */ public BigDecimal getBalanceByEmail(String email) { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .filter(account -> account.getEmail().equals(email)) + .map(Account::getBalance) + .findAny() + .orElseThrow(() -> new EntityNotFoundException("Cannot find Account by email=" + email)); } /** @@ -118,7 +145,9 @@ public BigDecimal getBalanceByEmail(String email) { * @return map of accounts by its ids */ public Map collectAccountsById() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .collect(toMap(Account::getId, identity())); } /** @@ -129,7 +158,10 @@ public Map collectAccountsById() { * @return map of account by its ids the were created in a particular year */ public Map collectBalancesByEmailForAccountsCreatedOn(int year) { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .filter(account -> account.getCreationDate().getYear() == year) + .collect(toMap(Account::getEmail, Account::getBalance)); } /** @@ -139,7 +171,10 @@ public Map collectBalancesByEmailForAccountsCreatedOn(int ye * @return a map where key is a last name and value is a set of first names */ public Map> groupFirstNamesByLastNames() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .collect(groupingBy(Account::getLastName, + mapping(Account::getFirstName, toSet()))); } /** @@ -149,7 +184,10 @@ public Map> groupFirstNamesByLastNames() { * @return a map where a key is a birthday month and value is comma-separated first names */ public Map groupCommaSeparatedFirstNamesByBirthdayMonth() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .collect(groupingBy(account -> account.getBirthday().getMonth(), + mapping(Account::getFirstName, joining(", ")))); } /** @@ -159,7 +197,10 @@ public Map groupCommaSeparatedFirstNamesByBirthdayMonth() { * @return a map where key is a creation month and value is total balance of all accounts created in that month */ public Map groupTotalBalanceByCreationMonth() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .collect(groupingBy(account -> account.getCreationDate().getMonth(), + mapping(Account::getBalance, reducing(BigDecimal.ZERO, BigDecimal::add)))); } /** @@ -169,7 +210,12 @@ public Map groupTotalBalanceByCreationMonth() { * @return a map where key is a letter and value is its count in all first names */ public Map getCharacterFrequencyInFirstNames() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .map(Account::getFirstName) + .flatMapToInt(String::chars) + .mapToObj(value -> (char) value) + .collect(groupingBy(identity(), counting())); } /** @@ -179,7 +225,12 @@ public Map getCharacterFrequencyInFirstNames() { * @return a map where key is a letter and value is its count ignoring case in all first and last names */ public Map getCharacterFrequencyIgnoreCaseInFirstAndLastNames() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + // todo: done + return accounts.stream() + .map(account -> account.getFirstName().toLowerCase() + account.getLastName().toLowerCase()) + .flatMapToInt(String::chars) + .mapToObj(value -> (char) value) + .collect(groupingBy(identity(), counting())); } } diff --git a/declarative-sum-of-squares/src/main/java/com/bobocode/SumOfSquares.java b/declarative-sum-of-squares/src/main/java/com/bobocode/SumOfSquares.java index fc0dfde..100a387 100644 --- a/declarative-sum-of-squares/src/main/java/com/bobocode/SumOfSquares.java +++ b/declarative-sum-of-squares/src/main/java/com/bobocode/SumOfSquares.java @@ -3,6 +3,8 @@ import com.bobocode.exception.InvalidRangeException; +import java.util.stream.IntStream; + /** * This class allow to calculate a sum of squares of integer number in a certain range. It was implemented using @@ -17,7 +19,7 @@ public static void main(String[] args) { * This method calculates the sum of squares of integer in the range * * @param startInclusive first element in range - * @param endInclusive last element in range + * @param endInclusive last element in range * @return the sum of squares of each element in the range */ static int calculateSumOfSquaresInRange(int startInclusive, int endInclusive) { @@ -25,11 +27,9 @@ static int calculateSumOfSquaresInRange(int startInclusive, int endInclusive) { throw new InvalidRangeException(); } - // todo: refactor using functional approach - int sumOfSquares = 0; - for (int i = startInclusive; i <= endInclusive; i++) { - sumOfSquares += i * i; - } - return sumOfSquares; + // todo: done + return IntStream.rangeClosed(startInclusive, endInclusive) + .map(i -> i * i) + .sum(); } } diff --git a/file-reader/src/main/java/com/bobocode/FileReaders.java b/file-reader/src/main/java/com/bobocode/FileReaders.java index 562a15b..0d302e0 100644 --- a/file-reader/src/main/java/com/bobocode/FileReaders.java +++ b/file-reader/src/main/java/com/bobocode/FileReaders.java @@ -1,5 +1,15 @@ package com.bobocode; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + /** * {@link FileReaders} privides an API that allow to read whole file into a {@link String} by file name. */ @@ -12,6 +22,18 @@ public class FileReaders { * @return string that holds whole file content */ public static String readWholeFile(String fileName) { - throw new UnsupportedOperationException("It's your job to make it work!"); //todo + //todo: done + try { + Objects.requireNonNull(fileName); + URL fileUrl = FileReaders.class.getClassLoader().getResource(fileName); + Path path = Paths.get(Objects.requireNonNull(fileUrl).toURI()); + +// return Files.lines(path).collect(Collectors.joining("\n")); + return String.join("\n", Files.readAllLines(path)); + } catch (URISyntaxException | IOException e) { + e.printStackTrace(); + } + + return ""; } }