Решение Задачи на стримы от Java Gym Rat
This commit is contained in:
@@ -1,26 +1,63 @@
|
||||
package com.algos.gym_rat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class OrderAnalysis {
|
||||
|
||||
// Рассчитать полную стоимость заказа
|
||||
public static Double calculateOrderTotal(Order order) {
|
||||
|
||||
return 0.0;
|
||||
return order
|
||||
.getProducts()
|
||||
.stream()
|
||||
.mapToDouble(p -> p.getQuantity() * p.getPrice())
|
||||
.sum();
|
||||
}
|
||||
|
||||
//Получить список наименований товаров из заказов
|
||||
public static Set<String> getUniqueProducts(List<Order> orders) {
|
||||
|
||||
return null;
|
||||
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) {
|
||||
|
||||
return null;
|
||||
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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user