Task here is to practise Maps & Collections.
We have 2 classes with its attributes in the brackets
1st Class: Client (String name, String lastName, Integer age, BigDecimal cash)
Below list of random clients in Main
List<Client> clients = List.of(
new Client("Ola", "Chrzaszcz", 34, new BigDecimal("200")),
new Client("Ala", "Kowalsky", 24, new BigDecimal("4000")),
new Client("Olaf", "Chrzaszcz", 19, new BigDecimal("3999")),
new Client("Piotr", "Nowak", 21, new BigDecimal("2099")),
new Client("Ola", "Szwed", 45, new BigDecimal("3000"))
)
;
2nd Class: Product (String name, Enum category, BigDecimal Price)
List<Product> products = List.of(
new Product("Szynka", Category.A, new BigDecimal(29)),
new Product("Ser", Category.B, new BigDecimal(22)),
new Product("Chleb", Category.C, new BigDecimal(6)),
new Product("Maslo", Category.D, new BigDecimal(4)),
new Product("Kielbasa", Category.A, new BigDecimal(25)),
new Product("Jajka", Category.A, new BigDecimal(8)),
new Product("Szynka", Category.C, new BigDecimal(25))
);
Based on these 2 list new Map is created (key: person, value: Map<Product, quantity of sold products)
//s1 - new map creation
Map<Client, Map<Product,Integer>> customersWithTheirShopping = new HashMap<>();
//adding values to the map
customersWithTheirShopping.put(clients.get(0), Map.of(products.get(0),5));
customersWithTheirShopping.put(clients.get(1), Map.of(products.get(1),6));
customersWithTheirShopping.put(clients.get(2), Map.of(products.get(6),16));
customersWithTheirShopping.put(clients.get(3), Map.of(products.get(5),11));
customersWithTheirShopping.put(clients.get(4), Map.of(products.get(4),5));
customersWithTheirShopping.put(clients.get(4), Map.of(products.get(3),6));
customersWithTheirShopping.put(clients.get(2), Map.of(products.get(2),8));
customersWithTheirShopping.put(clients.get(4), Map.of(products.get(1),9));
GOAL -> EXPECTED RESULTS: using stream to create method that return client with top money spent (price x quantity)
QUESTION:
- How to do it? How to get to the value of the map which is value itself?!
- As this is map and key (client) is unique, we can not expect duplication in instances of Client class, right (with this map structure)? It means that each customer can do order just once, right?
WHAT I DID -> CURRENT BEHAVIOUR:
public Client clientWithMostExpShoping() {
return quantitiesOfProductsBoughtByClient
.entrySet()
.stream()
.max(Comparator.comparing(p -> p.getValue().entrySet().stream().max(
Comparator.comparing(x -> x.getKey().getPrice().multiply(BigDecimal.valueOf(x.getValue()))))))
};
//btw did not find similar case unfortunately