I'm dealing with the following POJO:
@Getter
@AllArgsConstructor
public class Order {
private int quantity;
private Category category;
private LocalDate date;
//rest fields
}
I have a list of this objects and what I'm trying to do is I want to find month (extracted from date field) and category (which is enum type) which has the highest value of quantity. I wanna do it with streams, I made few attempts, but now I'm out of ideas. Could you help me with this?
Below my dummy attempt to resolve this case:
Optional<Entry<Month, Order>> result = orders.stream()
.collect(
Collectors.groupingBy(Order::getLocalDate, Collectors.maxBy(Comparator.comparingInt(Order::getQuantity))))
.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey().getMonth(), e -> e.getValue().get()))
.entrySet()
.stream()
.max(Entry.comparingByValue(Comparator.comparingInt(Order::getQuantity)));
Example, we have the following list of data:
List<Order> orders = Arrays.asList(
new Order(Category.HEADPHONES,3, LocalDate.of(2018, 2, 22)),
new Order(Category.HEADPHONES,6, LocalDate.of(2018, 2, 23)),
new Order(Category.NOTEBOOKS,8, LocalDate.of(2018, 2, 24)),
new Order(Category.NOTEBOOKS,4, LocalDate.of(2018, 3, 3)),
new Order(Category.NOTEBOOKS,1, LocalDate.of(2018, 3, 3)),
new Order(Category.PHONES,2, LocalDate.of(2018, 3,5)),
new Order(Category.PHONES,2, LocalDate.of(2018, 3,7))
);
I want to play with streams and receive the result (e.g some Tuple which contains month, category, quantity).
In the above data-set month with the highest quantity value (9) was February in HEADPHONES category.
Entry<Month, Order>if you need a summedquantityfrom a combination ofMonthandCategory? Shouldn't result be something likeEntry<Pair<Month, Category>, Integer>?