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
56 changes: 38 additions & 18 deletions crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
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.*;
import java.util.stream.Collectors;

public class CrazyOptionals {

Expand All @@ -24,7 +23,7 @@ public class CrazyOptionals {
* @return optional object that holds text
*/
public static Optional<String> optionalOfString(@Nullable String text) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
return Optional.ofNullable(text);
}

/**
Expand All @@ -34,7 +33,10 @@ public static Optional<String> 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");
accountProvider.getAccount()
.ifPresent(account -> {
account.setBalance(account.getBalance().add(amount));
});
}

/**
Expand All @@ -44,7 +46,7 @@ public static void deposit(AccountProvider accountProvider, BigDecimal amount) {
* @return optional object that holds account
*/
public static Optional<Account> optionalOfAccount(@Nonnull Account account) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
return Optional.of(account);
}

/**
Expand All @@ -56,7 +58,7 @@ public static Optional<Account> 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");
return accountProvider.getAccount().orElse(defaultAccount);
}

/**
Expand All @@ -67,7 +69,8 @@ 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");
accountProvider.getAccount()
.ifPresentOrElse(accountService::processAccount, accountService::processWithNoAccount);
}

/**
Expand All @@ -78,7 +81,8 @@ 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");
return accountProvider.getAccount()
.orElseGet(Accounts::generateAccount);
}

/**
Expand All @@ -88,7 +92,8 @@ public static Account getOrGenerateAccount(AccountProvider accountProvider) {
* @return optional balance
*/
public static Optional<BigDecimal> retrieveBalance(AccountProvider accountProvider) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
return accountProvider.getAccount()
.map(Account::getBalance);
}

/**
Expand All @@ -99,7 +104,7 @@ public static Optional<BigDecimal> 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");
return accountProvider.getAccount().orElseThrow(() -> new AccountNotFoundException("No Account provided!"));
}

/**
Expand All @@ -109,7 +114,8 @@ public static Account getAccount(AccountProvider accountProvider) {
* @return optional credit balance
*/
public static Optional<BigDecimal> retrieveCreditBalance(CreditAccountProvider accountProvider) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
return accountProvider.getAccount()
.flatMap(CreditAccount::getCreditBalance);
}


Expand All @@ -121,7 +127,8 @@ public static Optional<BigDecimal> retrieveCreditBalance(CreditAccountProvider a
* @return optional gmail account
*/
public static Optional<Account> retrieveAccountGmail(AccountProvider accountProvider) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
return accountProvider.getAccount()
.filter(account -> account.getEmail().contains("gmail"));
}

/**
Expand All @@ -134,7 +141,7 @@ public static Optional<Account> 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");
return accountProvider.getAccount().or(fallbackProvider::getAccount).orElseThrow(NoSuchElementException::new);
}

/**
Expand All @@ -145,7 +152,9 @@ public static Account getAccountWithFallback(AccountProvider accountProvider, Ac
* @return account with the highest balance
*/
public static Account getAccountWithMaxBalance(List<Account> accounts) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
return accounts.stream()
.max(Comparator.comparing(Account::getBalance))
.orElseThrow(NoSuchElementException::new);
}

/**
Expand All @@ -155,7 +164,11 @@ public static Account getAccountWithMaxBalance(List<Account> accounts) {
* @return the lowest balance values
*/
public static OptionalDouble findMinBalanceValue(List<Account> accounts) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
Optional<Account> account = accounts.stream()
.min(Comparator.comparing(Account::getBalance));

return account.isPresent() ? OptionalDouble.of(account.get().getBalance().doubleValue()) : OptionalDouble.empty();

}

/**
Expand All @@ -165,7 +178,9 @@ public static OptionalDouble findMinBalanceValue(List<Account> accounts) {
* @param accountService
*/
public static void processAccountWithMaxBalance(List<Account> accounts, AccountService accountService) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
accounts.stream()
.max(Comparator.comparing(Account::getBalance))
.ifPresent(accountService::processAccount);
}

/**
Expand All @@ -175,7 +190,12 @@ public static void processAccountWithMaxBalance(List<Account> accounts, AccountS
* @return total credit balance
*/
public static double calculateTotalCreditBalance(List<CreditAccount> accounts) {
throw new UnsupportedOperationException("Some people say that method does not work until you implement it");
return accounts.stream()
.map(CreditAccount::getCreditBalance)
.map(b -> b.orElse(BigDecimal.ZERO).doubleValue())
.mapToDouble(Double::longValue)
.sum();

}
}

70 changes: 52 additions & 18 deletions crazy-streams/src/main/java/com.bobocode/CrazyStreams.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

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 static java.util.stream.Collectors.toMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* Implement methods using Stream API
Expand All @@ -29,7 +30,8 @@ private CrazyStreams(Collection<Account> accounts) {
* @return account with max balance wrapped with optional
*/
public Optional<Account> findRichestPerson() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.max(Comparator.comparing(Account::getBalance));
}

/**
Expand All @@ -39,7 +41,9 @@ public Optional<Account> findRichestPerson() {
* @return a list of accounts
*/
public List<Account> findAccountsByBirthdayMonth(Month birthdayMonth) {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.filter(a -> Objects.equals(a.getBirthday().getMonth(), birthdayMonth))
.collect(Collectors.toList());
}

/**
Expand All @@ -49,7 +53,8 @@ public List<Account> findAccountsByBirthdayMonth(Month birthdayMonth) {
* @return a map where key is true or false, and value is list of male, and female accounts
*/
public Map<Boolean, List<Account>> partitionMaleAccounts() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.collect(Collectors.partitioningBy(o -> o.getSex().equals(Sex.MALE)));
}

/**
Expand All @@ -59,7 +64,8 @@ public Map<Boolean, List<Account>> partitionMaleAccounts() {
* @return a map where key is an email domain and value is a list of all account with such email
*/
public Map<String, List<Account>> groupAccountsByEmailDomain() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.collect(Collectors.groupingBy(a -> a.getEmail().split("@")[1]));
}

/**
Expand All @@ -68,7 +74,11 @@ public Map<String, List<Account>> 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()
.map(a -> a.getFirstName() + a.getLastName())
.map(String::length)
.mapToInt(Integer::intValue)
.sum();
}

/**
Expand All @@ -77,7 +87,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);
}

/**
Expand All @@ -86,7 +98,10 @@ public BigDecimal calculateTotalBalance() {
* @return list of accounts sorted by first and last names
*/
public List<Account> sortByFirstAndLastNames() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.sorted(Comparator.comparing(Account::getLastName))
.sorted(Comparator.comparing(Account::getFirstName))
.collect(Collectors.toList());
}

/**
Expand All @@ -96,7 +111,8 @@ public List<Account> 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()
.anyMatch(account -> account.getEmail().contains(emailDomain));
}

/**
Expand All @@ -107,7 +123,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(a -> Objects.equals(a.getEmail(), email))
.findFirst()
.orElseThrow(() -> new EntityNotFoundException("Cannot find Account by email=" + email))
.getBalance();
}

/**
Expand All @@ -116,7 +136,8 @@ public BigDecimal getBalanceByEmail(String email) {
* @return map of accounts by its ids
*/
public Map<Long, Account> collectAccountsById() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.collect(Collectors.toMap(Account::getId, Function.identity()));
}

/**
Expand All @@ -127,7 +148,9 @@ public Map<Long, Account> collectAccountsById() {
* @return map of account by its ids the were created in a particular year
*/
public Map<String, BigDecimal> collectBalancesByIdForAccountsCreatedOn(int year) {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.collect(Collectors.filtering(account -> account.getCreationDate().getYear() == year,
Collectors.toMap(Account::getEmail, Account::getBalance)));
}

/**
Expand All @@ -137,7 +160,8 @@ public Map<String, BigDecimal> collectBalancesByIdForAccountsCreatedOn(int year)
* @return a map where key is a last name and value is a set of first names
*/
public Map<String, Set<String>> groupFirstNamesByLastNames() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.collect(Collectors.groupingBy(Account::getLastName, Collectors.mapping(Account::getFirstName, Collectors.toSet())));
}

/**
Expand All @@ -147,7 +171,8 @@ public Map<String, Set<String>> groupFirstNamesByLastNames() {
* @return a map where a key is a birthday month and value is comma-separated first names
*/
public Map<Month, String> groupCommaSeparatedFirstNamesByBirthdayMonth() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.collect(Collectors.groupingBy(account -> account.getBirthday().getMonth(), Collectors.mapping(Account::getFirstName, Collectors.joining(", "))));
}

/**
Expand All @@ -157,7 +182,8 @@ public Map<Month, String> groupCommaSeparatedFirstNamesByBirthdayMonth() {
* @return a map where key is a creation month and value is total balance of all accounts created in that month
*/
public Map<Month, BigDecimal> groupTotalBalanceByCreationMonth() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.collect(Collectors.groupingBy(account -> account.getCreationDate().getMonth(), Collectors.mapping(Account::getBalance, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
}

/**
Expand All @@ -167,7 +193,10 @@ public Map<Month, BigDecimal> groupTotalBalanceByCreationMonth() {
* @return a map where key is a letter and value is its count in all first names
*/
public Map<Character, Long> getCharacterFrequencyInFirstNames() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.map(Account::getFirstName)
.flatMap(firstName -> firstName.chars().mapToObj(character -> (char)character))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}

/**
Expand All @@ -177,7 +206,12 @@ public Map<Character, Long> getCharacterFrequencyInFirstNames() {
* @return a map where key is a letter and value is its count ignoring case in all first and last names
*/
public Map<Character, Long> getCharacterFrequencyIgnoreCaseInFirstAndLastNames() {
throw new UnsupportedOperationException("It's your job to implement this method"); // todo
return accounts.stream()
.map(account -> account.getFirstName()+account.getLastName())
.map(String::toLowerCase)
.flatMap(name -> name.chars().mapToObj(character -> (char) character))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

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
Expand All @@ -25,11 +26,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.range(startInclusive, endInclusive + 1)
.map(i -> i * i)
.sum();
}
}
Loading