Reputation:
So I have created a class that creates a map of keys that are string of names of dishes, each key has a set of string values that are the ingredients within the dish. I have managed to get all keys-value pairs to print, but now I want a method that takes a string as an argument and then if that string matches a key, print out the key-value pair, and if not, display an message saying no such key was found.
Here is my attempt:
public void printMapValue(String a) {
if (recipes.containsKey(a)) {
System.out.println("The ingredients for " + a + " Are: " + ingredients);
} else {
System.out.println("That string does not match a record");
}
}
Here is my full class code so far as well, which all works as intended up until the printMapVale()
method
public class Recipe {
Map<String, Set<String>> recipes;
public Recipe() {
this.recipes = new HashMap<>();
}
public void addData() {
Set<String> ingredients = new HashSet<>();
ingredients.add("Rice");
ingredients.add("Stock");
recipes.put("Risotto", ingredients);
ingredients = new HashSet<>();
ingredients.add("Bun");
ingredients.add("Patty");
ingredients.add("Cheese");
ingredients.add("Lettuce");
recipes.put("Burger", ingredients);
ingredients = new HashSet<>();
ingredients.add("Base");
ingredients.add("Sauce");
ingredients.add("Cheese");
ingredients.add("Pepperoni");
recipes.put("Pizza", ingredients);
}
public void printMap() {
for (String recipeKey : recipes.keySet()) {
System.out.print("Dish : " + String.valueOf(recipeKey) + " Ingredients:");
for (String dish : recipes.get(recipeKey)) {
System.out.print(" " + dish + " ");
}
System.out.println();
}
}
public void printMapValue(String a) {
if (recipes.containsKey(a)) {
System.out.println("The ingredients for " + a + " Are: " + recipes.keySet(a));
} else {
System.out.println("That string does not match a record");
}
}
}
Upvotes: 0
Views: 1244
Reputation: 469
With java 1.9+, it can be written
public void printMapValue(String a) {
recipes.entrySet().stream()
.filter(e -> a.equals(e.getKey()))
.findFirst().ifPresentOrElse(e -> System.out
.println("The ingredients for " + e.getKey() + " Are: " + e.getValue(),
System.out.println("That string does not match a record"));
}
Upvotes: 0
Reputation: 880
check following code,
public void printMapValue(String a) {
Set<String> resultSet = null;
for (Map.Entry<String, Set<String>> entry : recipes.entrySet()) {
if (entry.getKey().equals(a)) {
resultSet = entry.getValue();
System.out.println("The ingredients for " + a + " Are: " + resultSet);
}
}
if (Objects.isNull(resultSet)) {
System.out.println("That string does not match a record");
}
}
Upvotes: 0
Reputation: 44150
keySet
does not take any parameters. That methods returns the entire set of keys, in this case
[Risotto, Burger, Pizza]
You want to do a look-up which is the get
method.
System.out.println("The ingredients for " + a + " Are: " + recipes.get(a));
Upvotes: 3