package mi.hdm.recipes; import java.util.ArrayList; import java.util.List; public class RecipeSearch { private final List<Recipe> recipesToSearch; public RecipeSearch (List<Recipe> recipesToSearch) { this.recipesToSearch = recipesToSearch; } /** * A method to search a list of recipes for keywords. * The method searches the recipe names and the ingredients for the keywords. * * @param query a String with keywords to search for * @return a list of Recipes which contain one or several of the keywords in its name or its ingredients */ public List<Recipe> searchByQuery(String query) { //TODO: filter out chars like ! ? . : etc if (query == null || query.isBlank()) return recipesToSearch; List<Recipe> result = new ArrayList<>(); String[] split = query.split(" "); //split String into separate words and put them into a String Array for (final Recipe r : recipesToSearch) { //search all recipes from recipesToSearch for (final String s : split) { String l = s.toLowerCase(); //convert current string of the query to lowercase! if (r.getName().toLowerCase().contains(l)) { //check if recipe name contains words from query (convert name of recipe to lowercase too) result.add(r); } for (final RecipeComponent c : r.getIngredients().keySet()) { if (c.getName().toLowerCase().contains(l)) { //check if ingredients contain words from query result.add(r); } } } } return result; } /** A method to search a list of recipes for categories. * The method filters recipes which belong to all requested categories. * * @param categoriesToSearch a list of categories to which the recipes shall belong * @return a list of recipes which belong to all categories of categoriesToSearch */ public List<Recipe> searchByCategory(List<Category> categoriesToSearch) { if (categoriesToSearch == null || categoriesToSearch.isEmpty()) return recipesToSearch; List<Recipe> result = new ArrayList<>(recipesToSearch); //create List containing all the recipes to search for (final Recipe r : recipesToSearch) { for (final Category c : categoriesToSearch) { if (!r.getCategories().contains(c)) { //if a recipe does not contain one of the categories it will be removed from the result set result.remove(r); } } } return result; } }