Skip to content
Closed

Train #192

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
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,15 @@

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.StreamSupport;

/**
* {@link CrazyGenerics} is an exercise class. It consists of classes, interfaces and methods that should be updated
Expand All @@ -33,8 +39,8 @@ public class CrazyGenerics {
* @param <T> – value type
*/
@Data
public static class Sourced { // todo: refactor class to introduce type parameter and make value generic
private Object value;
public static class Sourced<T> { // todo: refactor class to introduce type parameter and make value generic
private T value;
private String source;
}

Expand All @@ -45,11 +51,11 @@ public static class Sourced { // todo: refactor class to introduce type paramete
* @param <T> – actual, min and max type
*/
@Data
public static class Limited {
public static class Limited<T extends Number> {
// todo: refactor class to introduce type param bounded by number and make fields generic numbers
private final Object actual;
private final Object min;
private final Object max;
private final T actual;
private final T min;
private final T max;
}

/**
Expand All @@ -59,8 +65,10 @@ public static class Limited {
* @param <T> – source object type
* @param <R> - converted result type
*/
public interface Converter { // todo: introduce type parameters
public interface Converter<T, R> { // todo: introduce type parameters
// todo: add convert method

R convert(T source);
}

/**
Expand All @@ -70,10 +78,10 @@ public interface Converter { // todo: introduce type parameters
*
* @param <T> – value type
*/
public static class MaxHolder { // todo: refactor class to make it generic
private Object max;
public static class MaxHolder<T extends Comparable<? super T>> { // todo: refactor class to make it generic
private T max;

public MaxHolder(Object max) {
public MaxHolder(T max) {
this.max = max;
}

Expand All @@ -82,11 +90,13 @@ public MaxHolder(Object max) {
*
* @param val a new value
*/
public void put(Object val) {
throw new ExerciseNotCompletedException(); // todo: update parameter and implement the method
public void put(T val) {
if (val.compareTo(getMax()) > 0) {
max = val;
}
}

public Object getMax() {
public T getMax() {
return max;
}
}
Expand All @@ -97,8 +107,8 @@ public Object getMax() {
*
* @param <T> – the type of objects that can be processed
*/
interface StrictProcessor { // todo: make it generic
void process(Object obj);
interface StrictProcessor<T extends Comparable<? super T> & Serializable> { // todo: make it generic
void process(T obj);
}

/**
Expand All @@ -108,10 +118,10 @@ interface StrictProcessor { // todo: make it generic
* @param <T> – a type of the entity that should be a subclass of {@link BaseEntity}
* @param <C> – a type of any collection
*/
interface CollectionRepository { // todo: update interface according to the javadoc
void save(Object entity);
interface CollectionRepository<T extends BaseEntity, C extends Collection<T>> { // todo: update interface according to the javadoc
void save(T entity);

Collection<Object> getEntityCollection();
C getEntityCollection();
}

/**
Expand All @@ -120,7 +130,7 @@ interface CollectionRepository { // todo: update interface according to the java
*
* @param <T> – a type of the entity that should be a subclass of {@link BaseEntity}
*/
interface ListRepository { // todo: update interface according to the javadoc
interface ListRepository<T extends BaseEntity> extends CollectionRepository<T, List<T>> { // todo: update interface according to the javadoc
}

/**
Expand All @@ -133,7 +143,11 @@ interface ListRepository { // todo: update interface according to the javadoc
*
* @param <E> a type of collection elements
*/
interface ComparableCollection { // todo: refactor it to make generic and provide a default impl of compareTo
interface ComparableCollection<E> extends Collection<E>, Comparable<Collection<?>> {
@Override
default int compareTo(Collection<?> other) {
return Integer.compare(this.size(), other.size());
}
}

/**
Expand All @@ -147,7 +161,7 @@ static class CollectionUtil {
*
* @param list
*/
public static void print(List<Integer> list) {
public static void print(List<?> list) {
// todo: refactor it so the list of any type can be printed, not only integers
list.forEach(element -> System.out.println(" – " + element));
}
Expand All @@ -160,8 +174,8 @@ public static void print(List<Integer> list) {
* @param entities provided collection of entities
* @return true if at least one of the elements has null id
*/
public static boolean hasNewEntities(Collection<BaseEntity> entities) {
throw new ExerciseNotCompletedException(); // todo: refactor parameter and implement method
public static boolean hasNewEntities(Collection<? extends BaseEntity> entities) {
return entities.stream().anyMatch(entity -> entity.getUuid() == null);
}

/**
Expand All @@ -173,8 +187,8 @@ public static boolean hasNewEntities(Collection<BaseEntity> entities) {
* @param validationPredicate criteria for validation
* @return true if all entities fit validation criteria
*/
public static boolean isValidCollection() {
throw new ExerciseNotCompletedException(); // todo: add method parameters and implement the logic
public static boolean isValidCollection(Collection<? extends BaseEntity> collection, Predicate<? super BaseEntity> validationPredicate) {
return collection.stream().allMatch(validationPredicate);
}

/**
Expand All @@ -187,8 +201,10 @@ public static boolean isValidCollection() {
* @param <T> entity type
* @return true if entities list contains target entity more than once
*/
public static boolean hasDuplicates() {
throw new ExerciseNotCompletedException(); // todo: update method signature and implement it
public static <T extends BaseEntity> boolean hasDuplicates(List<T> entities, T targetEntity) {
return entities.stream()
.filter(entity -> entity.getUuid().equals(targetEntity.getUuid()))
.count() > 1;
}

/**
Expand All @@ -201,6 +217,18 @@ public static boolean hasDuplicates() {
* @return optional max value
*/
// todo: create a method and implement its logic manually without using util method from JDK
public static <T extends BaseEntity> Optional<T> findMax(Iterable<T> elements, Comparator<? super BaseEntity> comparator) {
// T max = null;
// for (T element : elements) {
// if (max == null || comparator.compare(element, max) > 0) {
// max = element;
// }
// }
// return Optional.ofNullable(max);
return StreamSupport.stream(elements.spliterator(), false)
.max(comparator);

}

/**
* findMostRecentlyCreatedEntity is a generic util method that accepts a collection of entities and returns the
Expand All @@ -215,6 +243,9 @@ public static boolean hasDuplicates() {
* @return an entity from the given collection that has the max createdOn value
*/
// todo: create a method according to JavaDoc and implement it using previous method
public static <T extends BaseEntity> T findMostRecentlyCreatedEntity(Collection<? extends T> entities) {
return findMax(entities, CREATED_ON_COMPARATOR).orElseThrow(NoSuchElementException::new);
}

/**
* An util method that allows to swap two elements of any list. It changes the list so the element with the index
Expand All @@ -226,10 +257,27 @@ public static boolean hasDuplicates() {
* @param j index of the other element to swap
*/
public static void swap(List<?> elements, int i, int j) {

Objects.checkIndex(i, elements.size());
Objects.checkIndex(j, elements.size());
throw new ExerciseNotCompletedException(); // todo: complete method implementation

//#1 Collections.swap(elements, i, j);


// // #2 OR Swap elements manually
// List<Object> rawList = (List<Object>) elements;
// Object temp = rawList.get(i);
// rawList.set(i, rawList.get(j));
// rawList.set(j, temp);

swapHelper(elements, i, j);
}
public static <T> void swapHelper(List<T> elements, int i, int j) {
T temp = elements.get(i);
elements.set(i, elements.get(j));
elements.set(j, temp);
}


}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.bobocode.basics;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import static java.util.Comparator.naturalOrder;

/**
* {@link HeterogeneousMaxHolder} is a multi-type container that holds maximum values per each type. It's kind of a
* key/value map, where the key is a type and the value is the maximum among all values of this type that were put.
Expand All @@ -14,8 +18,8 @@
*
* @author Taras Boychuk
*/
public class HeterogeneousMaxHolder {

public class HeterogeneousMaxHolder {
private static Map<Class<?>, Object> maxValueMap = new HashMap<>();
/**
* A method put stores a provided value by its type, if the value is greater than the current maximum. In other words, the logic
* of this method makes sure that only max value is stored and everything else is ignored.
Expand All @@ -31,6 +35,9 @@ public class HeterogeneousMaxHolder {
* @return a smaller value among the provided value and the current maximum
*/
// todo: implement a method according to javadoc
public static <T extends Comparable<? super T>> T put(Class<T> key, T value) {
return put(key, value, naturalOrder());
}

/**
* An overloaded method put implements the same logic using a custom comparator. A given comparator is wrapped with
Expand All @@ -45,7 +52,14 @@ public class HeterogeneousMaxHolder {
* @return a smaller value among the provided value and the current maximum
*/
// todo: implement a method according to javadoc

public static <T> T put(Class<T> key, T value, Comparator<? super T> comparator) {
comparator = Comparator.nullsFirst(comparator);
T currentMax = key.cast( maxValueMap.get(key));
if (comparator.compare(value, currentMax) > 0) {
return key.cast( maxValueMap.put(key, value)) ;
}
return value;
}
/**
* A method getMax returns a max value by the given type. If no value is stored by this type, then it returns null.
*
Expand All @@ -54,4 +68,8 @@ public class HeterogeneousMaxHolder {
* @return current max value or null
*/
// todo: implement a method according to javadoc

public static <T> T getMax(Class<T> key) {
return key.cast( maxValueMap.get(key));
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.bobocode.oop.data;

import com.bobocode.oop.service.Flights;
import com.bobocode.util.ExerciseNotCompletedException;

import java.util.HashSet;
Expand All @@ -12,7 +13,7 @@
* todo: 1. Implement a method {@link FlightDao#register(String)} that store new flight number into the set
* todo: 2. Implement a method {@link FlightDao#findAll()} that returns a set of all flight numbers
*/
public class FlightDao {
public class FlightDao implements Flights {
private Set<String> flights = new HashSet<>();

/**
Expand All @@ -22,7 +23,7 @@ public class FlightDao {
* @return {@code true} if a flight number was stored, {@code false} otherwise
*/
public boolean register(String flightNumber) {
throw new ExerciseNotCompletedException();// todo: implement this method
return flights.add(flightNumber);
}

/**
Expand All @@ -31,7 +32,6 @@ public boolean register(String flightNumber) {
* @return a set of flight numbers
*/
public Set<String> findAll() {
throw new ExerciseNotCompletedException();// todo: implement this method
return flights;
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.bobocode.oop.factory;

import com.bobocode.oop.data.FlightDao;
import com.bobocode.oop.service.FlightService;
import com.bobocode.util.ExerciseNotCompletedException;

Expand All @@ -10,12 +11,14 @@
*/
public class FlightServiceFactory {


/**
* Create a new instance of {@link FlightService}
*
* @return FlightService
*/
public FlightService creteFlightService() {
throw new ExerciseNotCompletedException();

return new FlightService(new FlightDao());
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package com.bobocode.oop.service;

import com.bobocode.oop.data.FlightDao;
import com.bobocode.util.ExerciseNotCompletedException;

import java.util.List;
import java.util.Set;

import static java.util.stream.Collectors.toList;

/**
* {@link FlightService} provides an API that allows to manage flight numbers
Expand All @@ -12,14 +16,20 @@
*/
public class FlightService {

private Flights flights;

public FlightService(Flights flights) {
this.flights = flights;
}

/**
* Adds a new flight number
*
* @param flightNumber a flight number to add
* @return {@code true} if a flight number was added, {@code false} otherwise
*/
public boolean registerFlight(String flightNumber) {
throw new ExerciseNotCompletedException();
return flights.register(flightNumber);
}

/**
Expand All @@ -29,6 +39,8 @@ public boolean registerFlight(String flightNumber) {
* @return a list of found flight numbers
*/
public List<String> searchFlights(String query) {
throw new ExerciseNotCompletedException();
return flights.findAll().stream()
.filter(flightNum -> flightNum.toUpperCase().contains(query.toUpperCase()))
.collect(toList());
}
}
Loading