Search code examples
javaarraylisthashmap

How to fill a hashmap with an arraylist?


It kinda speaks for itself but how do I fill this?

Map<Integer,ArrayList<Integer>>intMap = new HashMap<Integer, ArrayList<Integer>>();

I've already tried

intMap.put(1, 2);
intMap.put(1, 3); etc

and

intMap.put(1, (2, 3);

Solution

  • You should use Map.computeIfAbsent:

    intMap.computeIfAbsent(someKey, k -> new ArrayList<>()).add(someValue);
    

    For example, to have these mappings:

    1 -> [2, 3]
    5 -> [8]
    6 -> [7, 9, 4]
    

    You could do it this way:

    intMap.computeIfAbsent(1, k -> new ArrayList<>()).add(2);
    intMap.computeIfAbsent(1, k -> new ArrayList<>()).add(3);
    
    intMap.computeIfAbsent(5, k -> new ArrayList<>()).add(8);
    
    intMap.computeIfAbsent(6, k -> new ArrayList<>()).add(7);
    intMap.computeIfAbsent(6, k -> new ArrayList<>()).add(9);
    intMap.computeIfAbsent(6, k -> new ArrayList<>()).add(4);
    

    EDIT:

    Map.computeIfAbsent is equivalent to this code:

    List<Integer> list = intMap.get(someKey);
    if (list == null) {
        list = new ArrayList<>();
        intMap.put(someKey, list);
    }
    list.add(someValue);