将新的键值添加到现有的HashMap

时间:2018-04-27 10:54:03

标签: java collections hashmap treeset

我尝试将新的Key / Value添加到现有的HashMap(bandMap),其中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)
}
}

1 个答案:

答案 0 :(得分:1)

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

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]
}