Skip to content

Instantly share code, notes, and snippets.

@GayanM
Created September 21, 2022 07:36
Show Gist options
  • Select an option

  • Save GayanM/d70bd85236d1f8fcb0b305e81c7fe0f5 to your computer and use it in GitHub Desktop.

Select an option

Save GayanM/d70bd85236d1f8fcb0b305e81c7fe0f5 to your computer and use it in GitHub Desktop.
Filter products by category and price range
@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