我面临一个棘手的情况,我必须在具有嵌套列表的对象上使用 groupingBy。我用 map()、flatmap()、toMap() 尝试了一些东西,但无法提出解决方案,只能绕圈子。非常感谢流专家的任何帮助。我需要在我的 OrdersAnalyzer 类中实现 2 个方法。这是我的对象的样子:
public class Order {
private final String id;
private final Set<OrderLine> orderLines = new HashSet<>();
private final Customer customer;
//getters, setters, equals, hashcode omitted for brevity
}
public class OrderLine {
private final Product product;
private final Integer quantity;
//getters, setters, equals, hashcode omitted for brevity
}
public class Product {
private final String name;
private final BigDecimal price;
//getters, setters, equals, hashcode omitted for brevity
}
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) {
orders.forEach(order -> {
order.getOrderLines().stream().collect(
Collectors.groupingBy(OrderLine::getProduct, *What to add here?* )
);
});
}
/**
* 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) {
orders.collect(
Collectors.groupingBy(Order::getCustomer, *What to add here?*)
);
}
}