Storing and Retrieving ArrayList values from hashmap

后端 未结 7 2540
感动是毒
感动是毒 2020-12-13 13:27

I have a hashmap of the following type

HashMap> map=new HashMap>();    
<         


        
7条回答
  •  误落风尘
    2020-12-13 13:34

    Our variable:

    Map> map = new HashMap>();
    

    To store:

    map.put("mango", new ArrayList(Arrays.asList(0, 4, 8, 9, 12)));
    

    To add numbers one and one, you can do something like this:

    String key = "mango";
    int number = 42;
    if (map.get(key) == null) {
        map.put(key, new ArrayList());
    }
    map.get(key).add(number);
    

    In Java 8 you can use putIfAbsent to add the list if it did not exist already:

    map.putIfAbsent(key, new ArrayList());
    map.get(key).add(number);
    

    Use the map.entrySet() method to iterate on:

    for (Entry> ee : map.entrySet()) {
        String key = ee.getKey();
        List values = ee.getValue();
        // TODO: Do something.
    }
    

提交回复
热议问题