diff --git a/account-analytics/src/main/java/com.bobocode/AccountAnalytics.java b/account-analytics/src/main/java/com.bobocode/AccountAnalytics.java index 8c825fb..0b7bdff 100644 --- a/account-analytics/src/main/java/com.bobocode/AccountAnalytics.java +++ b/account-analytics/src/main/java/com.bobocode/AccountAnalytics.java @@ -2,10 +2,17 @@ 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.*; +import java.util.function.Function; +import java.util.stream.Stream; + +import static java.util.Comparator.comparing; +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.*; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toMap; @@ -30,7 +37,8 @@ private AccountAnalytics(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 + return accounts.stream() + .max(comparing(Account::getBalance)); } /** @@ -40,7 +48,9 @@ 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 + return accounts.stream() + .filter(a -> a.getBirthday().getMonth().equals(birthdayMonth)) + .collect(toList()); } /** @@ -50,7 +60,8 @@ 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 + return accounts.stream() + .collect(partitioningBy(a -> a.getSex().equals(Sex.MALE))); } /** @@ -60,7 +71,8 @@ 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 + return accounts.stream() + .collect(groupingBy(a -> a.getEmail().split("@")[1])); } /** @@ -69,7 +81,9 @@ 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 + return accounts.stream() + .mapToInt(a -> a.getFirstName().length() + a.getLastName().length()) + .sum(); } /** @@ -78,7 +92,9 @@ public int getNumOfLettersInFirstAndLastNames() { * @return total balance of all accounts */ public BigDecimal calculateTotalBalance() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + return accounts.stream() + .map(Account::getBalance) + .reduce(BigDecimal.ZERO, BigDecimal::add); } /** @@ -87,7 +103,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 + return accounts.stream() + .sorted(comparing(Account::getFirstName) + .thenComparing(Account::getLastName)) + .collect(toList()); } /** @@ -97,7 +116,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 + return accounts.stream() + .map(Account::getEmail) + .anyMatch(email -> email.split("@")[1].equals(emailDomain)); } /** @@ -108,7 +129,11 @@ 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 + return accounts.stream() + .filter(account -> account.getEmail().equals(email)) + .findFirst() + .map(Account::getBalance) + .orElseThrow(() -> new EntityNotFoundException(String.format("Cannot find Account by email=%s", email))); } /** @@ -117,7 +142,8 @@ 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 + return accounts.stream() + .collect(toMap(Account::getId, identity())); } /** @@ -128,7 +154,9 @@ public Map collectAccountsById() { * @return map of account by its ids the were created in a particular year */ public Map collectBalancesByIdForAccountsCreatedOn(int year) { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + return accounts.stream() + .filter(account -> account.getCreationDate().getYear() == year) + .collect(toMap(Account::getEmail, Account::getBalance)); } /** @@ -138,7 +166,8 @@ public Map collectBalancesByIdForAccountsCreatedOn(int year) * @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 + return accounts.stream() + .collect(groupingBy(Account::getLastName, mapping(Account::getFirstName, toSet()))); } /** @@ -148,7 +177,9 @@ 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 + return accounts.stream() + .collect(groupingBy(a -> a.getBirthday().getMonth(), + mapping(Account::getFirstName, joining(", ")))); } /** @@ -158,7 +189,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 + return accounts.stream() + .collect(groupingBy(a -> a.getCreationDate().getMonth(), + mapping(Account::getBalance, + reducing(BigDecimal.ZERO, BigDecimal::add)))); } /** @@ -168,7 +202,11 @@ 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 + return accounts.stream() + .map(Account::getFirstName) + .flatMapToInt(String::chars) + .mapToObj(c -> (char) c) + .collect(groupingBy(identity(), counting())); } /** @@ -178,7 +216,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 + return accounts.stream() + .flatMap(a -> Stream.of(a.getFirstName(), a.getLastName())) + .map(String::toLowerCase) + .flatMapToInt(String::chars) + .mapToObj(c -> (char) c) + .collect(groupingBy(identity(), counting())); } } diff --git a/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java b/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java index 966d72c..6a329f1 100644 --- a/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java +++ b/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java @@ -1,8 +1,8 @@ package com.bobocode; import java.math.BigDecimal; +import java.util.concurrent.ThreadLocalRandom; import java.util.Map; -import java.util.TreeMap; import java.util.function.*; public class CrazyLambdas { @@ -13,7 +13,7 @@ public class CrazyLambdas { * @return a string supplier */ public static Supplier helloSupplier() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + return () -> "Hello"; } /** @@ -22,7 +22,7 @@ public static Supplier helloSupplier() { * @return a string predicate */ public static Predicate isEmptyPredicate() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + return String::isEmpty; } /** @@ -32,7 +32,7 @@ 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 + return String::repeat; } /** @@ -42,7 +42,7 @@ 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 + return bigDecimal -> "$" + bigDecimal; } /** @@ -54,7 +54,7 @@ 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 + return str -> str.length() >= min && str.length() < max; } /** @@ -63,7 +63,7 @@ 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 + return () -> ThreadLocalRandom.current().nextInt(); } @@ -73,7 +73,7 @@ public static IntSupplier randomIntSupplier() { * @return int operation */ public static IntUnaryOperator boundedRandomIntSupplier() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + return bound -> ThreadLocalRandom.current().nextInt(bound); } /** @@ -82,7 +82,7 @@ public static IntUnaryOperator boundedRandomIntSupplier() { * @return square operation */ public static IntUnaryOperator intSquareOperation() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + return a -> a * a; } /** @@ -91,7 +91,7 @@ public static IntUnaryOperator intSquareOperation() { * @return binary sum operation */ public static LongBinaryOperator longSumOperation() { - throw new UnsupportedOperationException("It's your job to implement this method"); // todo + return (a, b) -> a + b; } /** @@ -100,7 +100,7 @@ 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 + return Integer::parseInt; } /** @@ -111,7 +111,7 @@ 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 + return () -> a -> n * a; } /** @@ -120,7 +120,7 @@ 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 + return stringFunction -> stringFunction.compose(String::trim); } /** @@ -131,7 +131,11 @@ 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 + return () -> { + Thread thread = new Thread(runnable); + thread.start(); + return thread; + }; } /** @@ -140,7 +144,7 @@ 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 + return runnable -> new Thread(runnable).start(); } /** @@ -150,7 +154,11 @@ 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 + return runnable -> () -> { + Thread thread = new Thread(runnable); + thread.start(); + return thread; + }; } /** @@ -163,7 +171,7 @@ 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 + return (intOperation, intPredicate) -> a -> intPredicate.test(a) ? intOperation.applyAsInt(a) : a; } /** @@ -174,7 +182,7 @@ 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 + return (functionMap, functionName) -> functionMap.getOrDefault(functionName, IntUnaryOperator.identity()); } /** @@ -183,7 +191,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 + return () -> () -> () -> "WELL DONE!"; } } + diff --git a/math-functions/src/main/java/com.bobocode/Functions.java b/math-functions/src/main/java/com.bobocode/Functions.java index 80ebc20..f983960 100644 --- a/math-functions/src/main/java/com.bobocode/Functions.java +++ b/math-functions/src/main/java/com.bobocode/Functions.java @@ -1,5 +1,7 @@ package com.bobocode; +import static java.lang.Math.abs; + public class Functions { /** * A static factory method that creates an integer function map with basic functions: @@ -14,7 +16,11 @@ public class Functions { public static FunctionMap intFunctionMap() { FunctionMap intFunctionMap = new FunctionMap<>(); - // todo: add simple functions to the function map (abs, sng, increment, decrement, square) + intFunctionMap.addFunction("square", n -> n * n); + intFunctionMap.addFunction("abs", Math::abs); + intFunctionMap.addFunction("increment", n -> n + 1); + intFunctionMap.addFunction("decrement", n -> n - 1); + intFunctionMap.addFunction("sgn", n -> (n != 0) ? n / abs(n) : 0); return intFunctionMap; } diff --git a/sum-of-squares/src/main/java/com/bobocode/SumOfSquares.java b/sum-of-squares/src/main/java/com/bobocode/SumOfSquares.java index fc0dfde..56736c2 100644 --- a/sum-of-squares/src/main/java/com/bobocode/SumOfSquares.java +++ b/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,8 @@ 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; + return IntStream.rangeClosed(startInclusive, endInclusive) + .map(a -> a * a) + .sum(); } } pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy