Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.es.orders;
- import com.es.orders.model.Customer;
- import com.es.orders.model.Order;
- import com.es.orders.model.OrderLine;
- import com.es.orders.model.Product;
- import java.math.BigDecimal;
- import java.time.Month;
- import java.util.Comparator;
- import java.util.List;
- import java.util.Map;
- import java.util.Optional;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- public class OrdersAnalyzer {
- /**
- * Should return at most three most popular products. Most popular product is the product that have the most occurrences
- * in given orders (ignoring product quantity).
- * If two products have the same popularity, then products should be ordered by name
- *
- * @param orders orders stream
- * @return list with up to three most popular products
- */
- public List<Product> findThreeMostPopularProducts(Stream<Order> orders) {
- Map<Product, Long> productsToOccurences = orders
- .flatMap(order -> order.getOrderLines().stream())
- .collect(
- Collectors.groupingBy(
- OrderLine::getProduct,
- Collectors.counting()
- )
- );
- return productsToOccurences.entrySet().stream()
- .sorted(Comparator
- .comparing(Map.Entry<Product, Long>::getValue).reversed()
- .thenComparing(entry -> entry.getKey().getName()))
- .map(Map.Entry::getKey)
- .limit(3)
- .collect(Collectors.toList());
- }
- /**
- * Should return the most valuable customer, that is the customer that has the highest value of all placed orders.
- * If two customers have the same orders value, then any of them should be returned.
- *
- * @param orders orders stream
- * @return Optional of most valuable customer
- */
- public Optional<Customer> findMostValuableCustomer(Stream<Order> orders) {
- Map<Customer, BigDecimal> customersToOrderValues = orders
- .collect(
- Collectors.groupingBy(
- Order::getCustomer,
- Collectors.reducing(
- BigDecimal.ZERO,
- this::countOrderValue,
- BigDecimal::add
- )
- )
- );
- return customersToOrderValues.entrySet().stream()
- .max(Comparator.comparing(Map.Entry::getValue))
- .map(Map.Entry::getKey);
- }
- /**
- * Should return the least busy month in current year to know when Petrovich can go on vacation.
- * The least busy month is the month in which the least number of possible repair works.
- *
- * @param orders orders stream
- * @return Optional of the least busy month in current year
- */
- public Optional<Month> findLeastBusyMonthInCurrentYear(Stream<Order> orders) {
- return null;
- }
- private BigDecimal countOrderValue(Order order) {
- return order.getOrderLines().stream()
- .map(line -> line.getProduct().getPrice().multiply(BigDecimal.valueOf(line.getQuantity())))
- .reduce(BigDecimal.ZERO, BigDecimal::add);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement