4

ネストされたリストを持つオブジェクトで 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?*)
      );
    }
}
4

1 に答える 1