We have been given a list of orders made by customers. The business team wants us to develop an API that would take input n and return all the customers who have made orders more than n times.
Our job is to return all the customers who have made orders more than n times.
All customers who made orders 2 or more times
List of Orders:
[Order(id=1, productId=2, customerId=1), Order(id=2, productId=1, customerId=3), Order(id=3, productId=3, customerId=3)]
List of Customers
[Customer(id=1, name=sam, age=65), Customer(id=2, name=lee, age=58), Customer(id=3, name=jane, age=40)]
[Customer(id=3, name=jane, age=30)]
- Only customer with ID 3 has made 2 or more orders.
Before jumping to the solution consider giving an attempt.
- First, let’s get all the input data and initialize orders and customers object.
// input data Common common = new Common(); List<Order> orders = common.getOrders(); List<Customer> customers = common.getCustomers();
- Since we have orders object we can group all the orders by their customer_id. by doing this we will get a map where customer_id -> [ order_1, order_2 …]
// 1: Group all the orders by the customer_id Map<Long, List<Order>> customerOrders = orders.stream() .collect(Collectors.groupingBy(Order::getCustomerId));
- Once we have a map ( where cutomer_id is mapped to their orders ), we can filter all the customer_ids who have 50 or more orders.
// 2: Filter all the customer_ids who made 50 or more orders List<Long> customerIds = customerOrders.entrySet().stream() .filter(a -> a.getValue().size() >= 50) .map(Map.Entry::getKey) .toList();
- Now the only thing that is left is to map the customer_id to the customer object. Since we have a List of Customer object, we can get the customer from customer_id.
// 3: Map customer_id to Customer in order to return the result. List<Customer> targetCustomers = customerIds.stream() .map(cid -> customers.stream().filter(c -> c.getId() == cid).findFirst()) .filter(Optional::isPresent) .map(Optional::get) .toList(); System.out.println(targetCustomers);
- Find all the code for this & other exercises on GitHub
In this problem, we used Java Stream API to solve it. Specifically, we used Grouping, Filter, Count and Map operations to get the result.
Before You Leave
- Upgrade your Java skills with Grokking the Java Interview.
- If you want to upskill your Java skills, you should definitely check out
[NEW] Master Spring Boot 3 & Spring Framework 6 with Java
[ 38 hrs content, 4.7/5 stars, 6+ students already enrolled]