如果字符串与键条目匹配,如何返回键及其值

时间:2019-05-08 08:54:58

标签: java hashmap key-value

因此,我创建了一个类,该类创建一个键映射,这些键是菜肴的名称字符串,每个键都有一组字符串值,这些值是菜肴中的成分。我设法打印了所有键-值对,但是现在我想要一个将字符串作为参数的方法,然后如果该字符串与键匹配,则打印出键-值对,否则显示一条消息说找不到这样的密钥。

这是我的尝试:

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");
    }
}

到目前为止,这也是我的完整课程代码,所有代码都按预期工作,直到使用printMapVale()方法

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");
        }
    }
}

3 个答案:

答案 0 :(得分:3)

keySet不带任何参数。在这种情况下,该方法将返回整个键集

[Risotto, Burger, Pizza]

您要执行get方法的查找。

System.out.println("The ingredients for " + a + " Are: " + recipes.get(a));

答案 1 :(得分:0)

检查以下代码,

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");
    }
}

答案 2 :(得分:0)

使用Java 1.9+可以编写

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"));
    }