diff --git a/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java b/crazy-lambdas/src/main/java/com/bobocode/CrazyLambdas.java index d5398ab..6e576cb 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,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"; } /** @@ -21,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; } /** @@ -31,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; } /** @@ -41,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 -> "$".concat(bigDecimal.toString()); } /** @@ -53,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 s -> min <= s.length() && s.length() < max; } /** @@ -62,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 () -> new Random().nextInt(); } @@ -72,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 operand -> new Random().nextInt(operand); } /** @@ -81,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 operand -> operand * operand; } /** @@ -90,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 (left, right) -> left + right; } /** @@ -99,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; } /** @@ -110,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 () -> x -> n * x; } /** @@ -119,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); } /** @@ -130,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; + }; } /** @@ -139,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(); } /** @@ -149,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; + }; } /** @@ -162,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 (intUnaryOperator, intPredicate) -> operand -> intPredicate.test(operand) ? intUnaryOperator.applyAsInt(operand) : operand; } /** @@ -173,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 (map, funcName) -> map.containsKey(funcName) ? map.get(funcName) : IntUnaryOperator.identity(); } /** @@ -182,7 +191,7 @@ 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/crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java b/crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java index d81fe02..8522fb1 100644 --- a/crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java +++ b/crazy-optionals/src/main/java/com/bobocode/CrazyOptionals.java @@ -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 { @@ -24,7 +23,7 @@ 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"); + return Optional.ofNullable(text); } /** @@ -34,7 +33,10 @@ 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"); + accountProvider.getAccount() + .ifPresent(account -> { + account.setBalance(account.getBalance().add(amount)); + }); } /** @@ -44,7 +46,7 @@ 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"); + return Optional.of(account); } /** @@ -56,7 +58,7 @@ 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"); + return accountProvider.getAccount().orElse(defaultAccount); } /** @@ -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); } /** @@ -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); } /** @@ -88,7 +92,8 @@ 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"); + return accountProvider.getAccount() + .map(Account::getBalance); } /** @@ -99,7 +104,7 @@ 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"); + return accountProvider.getAccount().orElseThrow(() -> new AccountNotFoundException("No Account provided!")); } /** @@ -109,7 +114,8 @@ 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"); + return accountProvider.getAccount() + .flatMap(CreditAccount::getCreditBalance); } @@ -121,7 +127,8 @@ 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"); + return accountProvider.getAccount() + .filter(account -> account.getEmail().contains("gmail")); } /** @@ -134,7 +141,7 @@ 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"); + return accountProvider.getAccount().or(fallbackProvider::getAccount).orElseThrow(NoSuchElementException::new); } /** @@ -145,7 +152,9 @@ 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"); + return accounts.stream() + .max(Comparator.comparing(Account::getBalance)) + .orElseThrow(NoSuchElementException::new); } /** @@ -155,7 +164,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"); + Optional account = accounts.stream() + .min(Comparator.comparing(Account::getBalance)); + + return account.isPresent() ? OptionalDouble.of(account.get().getBalance().doubleValue()) : OptionalDouble.empty(); + } /** @@ -165,7 +178,9 @@ 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"); + accounts.stream() + .max(Comparator.comparing(Account::getBalance)) + .ifPresent(accountService::processAccount); } /** @@ -175,7 +190,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"); + return accounts.stream() + .map(CreditAccount::getCreditBalance) + .map(b -> b.orElse(BigDecimal.ZERO).doubleValue()) + .mapToDouble(Double::longValue) + .sum(); + } } diff --git a/crazy-streams/src/main/java/com.bobocode/CrazyStreams.java b/crazy-streams/src/main/java/com.bobocode/CrazyStreams.java index 68731d7..9888bfa 100644 --- a/crazy-streams/src/main/java/com.bobocode/CrazyStreams.java +++ b/crazy-streams/src/main/java/com.bobocode/CrazyStreams.java @@ -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 @@ -29,7 +30,8 @@ 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 + return accounts.stream() + .max(Comparator.comparing(Account::getBalance)); } /** @@ -39,7 +41,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 -> Objects.equals(a.getBirthday().getMonth(), birthdayMonth)) + .collect(Collectors.toList()); } /** @@ -49,7 +53,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(Collectors.partitioningBy(o -> o.getSex().equals(Sex.MALE))); } /** @@ -59,7 +64,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(Collectors.groupingBy(a -> a.getEmail().split("@")[1])); } /** @@ -68,7 +74,11 @@ 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() + .map(a -> a.getFirstName() + a.getLastName()) + .map(String::length) + .mapToInt(Integer::intValue) + .sum(); } /** @@ -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); } /** @@ -86,7 +98,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(Comparator.comparing(Account::getLastName)) + .sorted(Comparator.comparing(Account::getFirstName)) + .collect(Collectors.toList()); } /** @@ -96,7 +111,8 @@ 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() + .anyMatch(account -> account.getEmail().contains(emailDomain)); } /** @@ -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(); } /** @@ -116,7 +136,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(Collectors.toMap(Account::getId, Function.identity())); } /** @@ -127,7 +148,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() + .collect(Collectors.filtering(account -> account.getCreationDate().getYear() == year, + Collectors.toMap(Account::getEmail, Account::getBalance))); } /** @@ -137,7 +160,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(Collectors.groupingBy(Account::getLastName, Collectors.mapping(Account::getFirstName, Collectors.toSet()))); } /** @@ -147,7 +171,8 @@ 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(Collectors.groupingBy(account -> account.getBirthday().getMonth(), Collectors.mapping(Account::getFirstName, Collectors.joining(", ")))); } /** @@ -157,7 +182,8 @@ 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(Collectors.groupingBy(account -> account.getCreationDate().getMonth(), Collectors.mapping(Account::getBalance, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)))); } /** @@ -167,7 +193,10 @@ 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) + .flatMap(firstName -> firstName.chars().mapToObj(character -> (char)character)) + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); } /** @@ -177,7 +206,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() + .map(account -> account.getFirstName()+account.getLastName()) + .map(String::toLowerCase) + .flatMap(name -> name.chars().mapToObj(character -> (char) character)) + .collect(Collectors.groupingBy(Function.identity(), Collectors.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..8b86c3a 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,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 @@ -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(); } } diff --git a/lambda-math-functions/src/main/java/com.bobocode/Functions.java b/lambda-math-functions/src/main/java/com.bobocode/Functions.java index 80ebc20..09d5076 100644 --- a/lambda-math-functions/src/main/java/com.bobocode/Functions.java +++ b/lambda-math-functions/src/main/java/com.bobocode/Functions.java @@ -1,5 +1,7 @@ package com.bobocode; +import java.util.function.Function; + public class Functions { /** * A static factory method that creates an integer function map with basic functions: @@ -14,8 +16,33 @@ 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("abs", Functions::abs); + intFunctionMap.addFunction("sgn", Functions::sgn); + intFunctionMap.addFunction("increment", Functions::increment); + intFunctionMap.addFunction("decrement", Functions::decrement); + intFunctionMap.addFunction("square", Functions::square); return intFunctionMap; } + + private static Integer abs(int number) { + return number < 0 ? number * -1 : number; + } + + private static Integer sgn(int number) { + if (number == 0) return 0; + return number < 0 ? -1 : 1; + } + + private static Integer increment(int number) { + return number + 1; + } + + private static Integer decrement(int number) { + return number - 1; + } + + private static Integer square(int number) { + return number * number; + } } diff --git a/linked-list/src/main/java/com/bobocode/LinkedList.java b/linked-list/src/main/java/com/bobocode/LinkedList.java index bd6176a..ec27d82 100644 --- a/linked-list/src/main/java/com/bobocode/LinkedList.java +++ b/linked-list/src/main/java/com/bobocode/LinkedList.java @@ -1,5 +1,7 @@ package com.bobocode; +import java.util.Arrays; + /** * {@link LinkedList} is a list implementation that is based on singly linked generic nodes. A node is implemented as * inner static class {@link Node}. In order to keep track on nodes, {@link LinkedList} keeps a reference to a head node. @@ -7,6 +9,8 @@ * @param generic type parameter */ public class LinkedList implements List { + private Node head; + private int size = 0; /** * This method creates a list of provided elements @@ -15,8 +19,12 @@ public class LinkedList implements List { * @param generic type * @return a new list of elements the were passed as method parameters */ - public static List of(T... elements) { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + @SafeVarargs + static List of(T... elements) { + List linkedList = new LinkedList<>(); + Arrays.stream(elements) + .forEach(linkedList::add); + return linkedList; } /** @@ -26,7 +34,14 @@ public static List of(T... elements) { */ @Override public void add(T element) { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + if (isEmpty()) { + head = new Node<>(element); + head.next = head; + head.prev = head; + size++; + } else { + insertNode(element, head); + } } /** @@ -38,7 +53,15 @@ public void add(T element) { */ @Override public void add(int index, T element) { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + if (index == 0) { + if (isEmpty()) { + add(element); + } else { + head = insertNode(element, head); + } + } else { + insertNode(element, findNode(index - 1).next); + } } /** @@ -50,7 +73,8 @@ public void add(int index, T element) { */ @Override public void set(int index, T element) { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + Node node = findNode(index); + node.value = element; } /** @@ -62,7 +86,7 @@ public void set(int index, T element) { */ @Override public T get(int index) { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + return findNode(index).value; } /** @@ -73,7 +97,20 @@ public T get(int index) { */ @Override public void remove(int index) { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + if (index == 0) { + Node newHead = head.next; + newHead.prev = head.prev; + head.prev.next = newHead; + head = newHead; + size--; + return; + } + Node node = findNode(index); + Node previousNode = node.prev; + + previousNode.next = node.next; + node.next.prev = previousNode; + size--; } @@ -84,7 +121,17 @@ public void remove(int index) { */ @Override public boolean contains(T element) { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + if (isEmpty()) { + return false; + } + Node node = head; + while(node.next != head) { + if (node.value == element) { + return true; + } + node = node.next; + } + return false; } /** @@ -94,7 +141,7 @@ public boolean contains(T element) { */ @Override public boolean isEmpty() { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + return size == 0; } /** @@ -104,7 +151,7 @@ public boolean isEmpty() { */ @Override public int size() { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + return size; } /** @@ -112,6 +159,44 @@ public int size() { */ @Override public void clear() { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + head = null; + size = 0; + } + + private Node findNode(int index) { + if (size - 1 < index || index < 0 || isEmpty()) { + throw new IndexOutOfBoundsException(); + } + Node node = head; + while(index > 0) { + index--; + node = node.next; + } + return node; + } + + private Node insertNode(T element, Node nextNode) { + Node newNode = new Node<>(element); + Node prevNode = nextNode.prev; + + newNode.prev = prevNode; + newNode.next = nextNode; + + prevNode.next = newNode; + nextNode.prev = newNode; + + size++; + + return newNode; + } + + private class Node { + private V value; + private Node next; + private Node prev; + + Node(V value) { + this.value = value; + } } } diff --git a/linked-queue/src/main/java/com/bobocode/LinkedQueue.java b/linked-queue/src/main/java/com/bobocode/LinkedQueue.java index 3cde892..8ed94c0 100644 --- a/linked-queue/src/main/java/com/bobocode/LinkedQueue.java +++ b/linked-queue/src/main/java/com/bobocode/LinkedQueue.java @@ -8,6 +8,9 @@ * @param a generic parameter */ public class LinkedQueue implements Queue { + private int size = 0; + private Node head; + private Node tale; /** * Adds an element to the end of the queue. @@ -15,7 +18,14 @@ public class LinkedQueue implements Queue { * @param element the element to add */ public void add(T element) { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + if (isEmpty()) { + head = new Node<>(element); + tale = head; + } else { + tale.next = new Node<>(element); + tale = tale.next; + } + size++; } /** @@ -24,7 +34,13 @@ public void add(T element) { * @return an element that was retrieved from the head or null if queue is empty */ public T poll() { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + if (isEmpty()) { + return null; + } + T value = head.value; + head = head.next; + size--; + return value; } /** @@ -33,7 +49,7 @@ public T poll() { * @return an integer value that is a size of queue */ public int size() { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + return size; } /** @@ -42,6 +58,15 @@ public int size() { * @return {@code true} if the queue is empty, returns {@code false} if it's not */ public boolean isEmpty() { - throw new UnsupportedOperationException("This method is not implemented yet"); // todo: implement this method + return size == 0; + } + + private class Node { + private Node next; + private V value; + + Node(V value) { + this.value = value; + } } }