63 lines
2.3 KiB
Java
63 lines
2.3 KiB
Java
package com.algos.gym_rat;
|
|
|
|
import java.util.*;
|
|
import java.util.stream.Collectors;
|
|
|
|
public class OrderAnalysis {
|
|
|
|
// Рассчитать полную стоимость заказа
|
|
public static Double calculateOrderTotal(Order order) {
|
|
|
|
return order
|
|
.getProducts()
|
|
.stream()
|
|
.mapToDouble(p -> p.getQuantity() * p.getPrice())
|
|
.sum();
|
|
}
|
|
|
|
//Получить список наименований товаров из заказов
|
|
public static Set<String> getUniqueProducts(List<Order> orders) {
|
|
|
|
return orders
|
|
.stream()
|
|
.flatMap(o -> o.getProducts().stream())
|
|
.map(Product::getName)
|
|
.collect(Collectors.toSet());
|
|
}
|
|
|
|
//Вывести наименования N популярных товаров в порядке уменьшения популярности
|
|
//Популярный товар - товар, который больше остальных покупается
|
|
public static List<String> findMostPopularProduct(List<Order> orders, int topN) {
|
|
|
|
Map<String, Integer> popularProducts = new HashMap<>();
|
|
for (Order order : orders) {
|
|
List<Product> products = order.getProducts();
|
|
for (Product product : products) {
|
|
popularProducts.merge(product.getName(), product.getQuantity(), Integer::sum);
|
|
}
|
|
}
|
|
|
|
return popularProducts
|
|
.entrySet()
|
|
.stream()
|
|
.sorted((e1, e2) -> {
|
|
return e2.getValue().compareTo(e1.getValue());
|
|
})
|
|
.limit(topN)
|
|
.map(Map.Entry::getKey)
|
|
.collect(Collectors.toList());
|
|
}
|
|
public static List<String> findMostPopularProductNice(List<Order> orders, int topN) {
|
|
|
|
return orders
|
|
.stream()
|
|
.flatMap(o -> o.getProducts().stream())
|
|
.collect(Collectors.groupingBy(Product::getName, Collectors.summingInt(Product::getQuantity)))
|
|
.entrySet()
|
|
.stream()
|
|
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
|
|
.limit(topN)
|
|
.map(Map.Entry::getKey)
|
|
.collect(Collectors.toList());
|
|
}
|
|
} |