如何将键值集添加到HashSet或覆盖键值集(如果已经存在)

时间:2019-05-08 23:11:37

标签: java key-value hashset

所以我有一个有效的哈希集,但是我需要添加一个带有两个参数(键字符串和设置字符串)的方法,该方法检查该键是否已存在于HashSet中,如果存在,则用新的设置值覆盖它,并如果没有创建,然后添加提供的值

我已经尝试过的代码是:

    public void addMapEntry(String dish, Set<String> ingredient){
    recipes.get(dish);
    if (recipes.containsKey(dish)) {
        recipes.replace(dish, ingredient);
    } else {
        recipes.put(dish, ingredient);
    }
}

到目前为止,完整类的代码为:

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.get(a));
    } else {
        System.out.println("That string does not match a record");
    }
}
public void addMapEntry(String dish, Set<String> ingredient){
    recipes.get(dish);
    if (recipes.containsKey(dish)) {
        recipes.replace(dish, ingredient);
    } else {
        recipes.put(dish, ingredient);
    }
}}

我收到错误找不到符号-方法replace(java.lang.String,java.util.Set)

我认为这意味着我可能需要在某处添加toString()!?

1 个答案:

答案 0 :(得分:0)

put()方法已经可以处理您感兴趣的覆盖和插入大小写。只需使用:

public void addMapEntry(String dish, Set<String> ingredient){
    recipes.put(dish, ingredient);
}
  

java.util.HashMap.put()的{​​{1}}方法用于将映射插入地图。这意味着我们可以将特定的键及其映射到的值插入到特定的映射中。 如果传递了现有键,则以前的值将被新值替换。如果传递了新对,则将整个键插入。

来源:https://www.geeksforgeeks.org/hashmap-put-method-in-java/