Adding a value to a list to an already existing key in Map

后端 未结 3 1688
自闭症患者
自闭症患者 2021-01-07 06:42

Evening!

I have the following Map:

HashMap myMap = new HashMap();

I then added th

3条回答
  •  生来不讨喜
    2021-01-07 07:00

    Simply get the list from the map and then add the element to the list:

    ArrayList list = myMap.get("Tests");
    list.add("Test4");
    

    There are some other things that can be remarked about your code. First of all, don't use the raw type ArrayList. Use generics:

    HashMap> myMap = new HashMap>();
    
    ArrayList myList = new ArrayList();
    myList.add("Test 1");
    myList.add("Test 2");
    myList.add("Test 3");
    myMap.put("Tests", myList);
    

    Second, program to interfaces, not implementations. In other words, program using interfaces Map and List rather than the implementations HashMap and ArrayList. This is a well-known OO programming principle, which makes it for example easier to switch to a different implementation, if necessary.

    Map> myMap = new HashMap>();
    
    List myList = new ArrayList();
    myList.add("Test 1");
    myList.add("Test 2");
    myList.add("Test 3");
    myMap.put("Tests", myList);
    

    Finally, a syntax tip: if you're using Java 7 or newer you can use <> and you don't have to repeat the type arguments:

    Map> myMap = new HashMap<>();
    
    List myList = new ArrayList<>();
    myList.add("Test 1");
    myList.add("Test 2");
    myList.add("Test 3");
    myMap.put("Tests", myList);
    
    myMap.get("Tests").add("Test 4");
    

提交回复
热议问题