将新的 Key-Value 添加到现有的 HashMap

Add a new Key-Value to an existing HashMap

我正在尝试向现有的 HashMap (bandMap) 添加一个新的 Key/Value,其中我的 test() 方法中的第二个参数必须是 Collection 类型。 由于我对 Java 还是很陌生,所以如果能提供任何解释方面的帮助,我们将不胜感激。

import java.util.*; 
public class Car
{
private Map<String, Set<String>> carMap = new HashMap<>(); //b
Set<String> model = new TreeSet<>();
/**
* Constructor for a Band object
*/
public void make()//b
{
Map<String, Set<String>> carMap = new HashMap<>();
}

/**
* Populate some sample data
*/
public void populate() //b
{

  model.add("Fiesta");
  model.add("Cougar");
  model.add("Transit");
  carMap.put("Ford", model);

  model = new TreeSet<>();
  model.add("Astra");
  model.add("Calibra");
  carMap.put("Vauxhall", model);

  model = new TreeSet<>();
  model.add("206");
  model.add("106");
  carMap.put("Peugeot", model);

 }

/**
* I need a method to add a new key - value pair
*/   

public void test(String makeName, Set<String> aModel)
{
 //Code to add new Key/Value to the exisiting HashMap (carMap)
}
}

您只需要 carMap 作为 class 变量。在您的 test() 方法中(我将其重命名为 addModel)只需像在 populate 方法中那样使用 put 方法。

public class Car {

    private Map<String, Set<String>> carMap = new HashMap<>();

    /**
     * Populate some sample data
     */
    public void populate() {

        Set<String> model = new TreeSet<>();
        model.add("Fiesta");
        model.add("Cougar");
        model.add("Transit");
        carMap.put("Ford", model);

        model = new TreeSet<>();
        model.add("Astra");
        model.add("Calibra");
        carMap.put("Vauxhall", model);

        model = new TreeSet<>();
        model.add("206");
        model.add("106");
        carMap.put("Peugeot", model);

    }

    public void addModel(String makeName, Set<String> aModel) {
        carMap.put(makeName, aModel);
    }

    public Map<String, Set<String>> getCarMap() {
        return carMap;
    }
}

那就这样用吧

public static void main(String[] args) {

    Car car = new Car();
    car.populate();
    car.addModel("AnotherBrand", new HashSet<>(Arrays.asList("a", "b")));
    System.out.println(car.getCarMap());

}

这将输出以下地图

{
    Vauxhall=[Astra, Calibra], 
    Ford=[Cougar, Fiesta, Transit], 
    AnotherBrand=[a, b], 
    Peugeot=[106, 206]
}