User_67128
User_67128

Reputation: 1250

Updating an entry of a HashMap whose values is a List

I have a HashMap<Integer, List<Integer>> "sq_diff" and I am trying to update an entry.

I tried:

List<Integer> values = sq_diff.get(diff);
values.add(c);
values.add(d);
sq_diff.put(diff, values);

and

sq_diff.get(diff).add(c);
sq_diff.get(diff).add(d);

and

sq_diff.computeIfPresent(diff, (k, v) -> v.add(c);
sq_diff.computeIfPresent(diff, (k, v) -> v.add(d);

None of them working:

Exception in thread "main" java.lang.UnsupportedOperationException

The map contains an entry of "diff"

Highly appreciated if you can indicate problems on each of them.

Upvotes: 2

Views: 434

Answers (2)

catch32
catch32

Reputation: 18572

Trouble is when you initialize your list by Arrays.asList(). As mentioned at the documentation:

This method also provides a convenient way to create a fixed-size list initialized to contain several elements

And later when you want to update your fixed-size list with adding new elements you got: UnsupportedOperationException.

As a soltion you can use a quite useful Guava's Lists utilities class:

Lists.newArrayList(c, d);

It also provides Maps utilities as well.

Code for it will look like:

public class MapDemo {
    public static void main(String[] args) {
        final int diff = 42;
        HashMap<Integer, List<Integer>> map = Maps.newHashMap();
        map.putIfAbsent(diff, Lists.newArrayList(1, 2));
        // 1:            
        final List<Integer> integers = map.get(diff);
        integers.add(10);
        integers.add(11);
        // 2: 
        map.get(diff).add(20);
        map.get(diff).add(21);
        // 3:    
        map.computeIfPresent(diff, (k, v) -> {
            v.add(30);
            return v;
        });
        map.computeIfPresent(diff, (k, v) -> {
            v.add(31);
            return v;
        });

        System.out.println(map);
    }
}

Output:

{42=[1, 2, 10, 11, 20, 21, 30, 31]}

As you can see all 3 cases are executed well.

Upvotes: 2

abhimanyue
abhimanyue

Reputation: 186

Try this,

List<Integer> values = new ArrayList<>(Arrays.asList(c, d));
sq_diff.put(diff, values);

instead of

sq_diff.put(diff, Arrays.asList(c, d));

Upvotes: 1

Related Questions