Storing and Retrieving ArrayList values from hashmap

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

I have a hashmap of the following type

HashMap> map=new HashMap>();    
<         


        
7条回答
  •  -上瘾入骨i
    2020-12-13 13:55

    The modern way (as of 2020) to add entries to a multimap (a map of lists) in Java is:

    map.computeIfAbsent("apple", k -> new ArrayList<>()).add(2);
    map.computeIfAbsent("apple", k -> new ArrayList<>()).add(3);
    

    According to Map.computeIfAbsent docs:

    If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

    Returns: the current (existing or computed) value associated with the specified key, or null if the computed value is null

    The most idiomatic way to iterate a map of lists is using Map.forEach and Iterable.forEach:

    map.forEach((k, l) -> l.forEach(v -> /* use k and v here */));
    

    Or, as shown in other answers, a traditional for loop:

    for (Map.Entry> e : map.entrySet()) {
        String k = e.getKey();
        for (Integer v : e.getValue()) {
            /* use k and v here */
        }
    }
    

提交回复
热议问题