Created
September 21, 2022 07:36
-
-
Save GayanM/d70bd85236d1f8fcb0b305e81c7fe0f5 to your computer and use it in GitHub Desktop.
Filter products by category and price range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @RequestMapping("") | |
| public List<Product> filterProducts(@Param("category") final Optional<String> category, | |
| @Param("lower-price-limit") final Optional<Double> lowerLimitPrice, | |
| @RequestParam("upper-price-limit") final Optional<Double> upperLimitPrice ) { | |
| return productRepos.findAll().stream(). | |
| filter(p -> { | |
| if (category.isEmpty()) { | |
| return true; | |
| } | |
| return category.get().equals(p.getCategory()); | |
| }). | |
| filter(p -> { | |
| if (lowerLimitPrice.isEmpty()) { | |
| return true; | |
| } | |
| return lowerLimitPrice.get() < p.getPrice(); | |
| }). | |
| filter(p -> { | |
| if (upperLimitPrice.isEmpty()) { | |
| return true; | |
| } | |
| return upperLimitPrice.get() > p.getPrice(); | |
| }). | |
| map(p -> { | |
| return new Product(p.getId(), p.getName(), p.getPrice(), p.getCategory()); | |
| } | |
| ).collect(Collectors.toList()); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment