Skip to content

Instantly share code, notes, and snippets.

@GayanM
Created September 25, 2022 11:12
Show Gist options
  • Save GayanM/23e7c5a101461bd2e2f5c9529e9fddad to your computer and use it in GitHub Desktop.
Save GayanM/23e7c5a101461bd2e2f5c9529e9fddad to your computer and use it in GitHub Desktop.
Get the most expensive product by category
@RequestMapping("/most-expensive")
Map<String, Optional<Product>> getMostExpensiveProductByCategory () {
Map<String, Optional<com.mycompany.functional.programming.exercises.models.Product>> mostExpensiveByCategory = productRepos.findAll().stream().collect(Collectors.groupingBy(
com.mycompany.functional.programming.exercises.models.Product::getCategory,
Collectors.maxBy(Comparator.comparing(com.mycompany.functional.programming.exercises.models.
Product::getPrice)
)
));
Map<String, Optional<Product>> ordersByCustomerTransformed = new HashMap();
mostExpensiveByCategory.entrySet().stream().forEach(e -> {
ordersByCustomerTransformed.put(e.getKey(), Optional.of(new Product(e.getValue().get().getId(),
e.getValue().get().getName(), e.getValue().get().getPrice(), e.getValue().get().getCategory())));
});
return ordersByCustomerTransformed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment