#525 Implementation of Logic in Product Category Service

Companies:
X5
Themes:
JavaCollections & GenericsPractice

Implement the logic in every place marked with TODO:

public interface ProductCategoryService {
    /**
     * The method is called once
     * and initializes the service with all products and categories.
     */
    void init(List<Product> products, List<Category> categories);


    /**
     * Checks whether a product belongs to a category.
     * It may be called frequently and many times.
     *
     * @param productId  product identifier
     * @param categoryId category identifier
     * @return {@code true} if the product belongs to the category,
     * otherwise {@code false}
     */
    boolean isProductInCategory(Long productId, Long categoryId);


    /**
     * Returns the list of products for a category.
     * Products must be sorted by name.
     * It may be called frequently and many times.
     *
     * @param categoryId category identifier
     * @return the list of products belonging to the category,
     * or an empty list if no products belong to the category
     */
    Collection<Product> getProductsByCategory(Long categoryId);
}

public interface Category {

    Long getId();

    String getName();

}

public interface Product {

    Long getId();

    String getName();

    List<Category> getCategories();

}


public class ProductCategoryServiceImpl implements ProductCategoryService {
    /**
     * The method is called once
     * and initializes the service with all products and categories.
     */
    @Override
    public void init(List<Product> products, List<Category> categories) {
        // TODO implement
    }


    /**
     * Checks whether a product belongs to a category.
     * It may be called frequently and many times.
     *
     * @param productId  product identifier
     * @param categoryId category identifier
     * @return {@code true} if the product belongs to the category,
     * otherwise {@code false}
     */
    @Override
    public boolean isProductInCategory(Long productId, Long categoryId) {
        // TODO implement
        return false;
    }


    /**
     * Returns the list of products for a category.
     * Products must be sorted by name.
     * It may be called frequently and many times.
     *
     * @param categoryId category identifier
     * @return the list of products belonging to the category,
     * or an empty list if no products belong to the category
     */
    @Override
    public Collection<Product> getProductsByCategory(Long categoryId) {
        // TODO implement
        return null;
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in