Skip to content
Advertisement

How can I use merge method in Java to append elements to the list value in map<Character,List>?

I am trying to understand the merge method. I have a map of <Character, List<Integer>>. I want to add the indices to the list of the appropriate key. I want to use the merge method to do so. I tried the following method. I am getting UnsupportedOperationException. What is the best way to do so using the merge method?

JavaScript

Advertisement

Answer

Wrap Arrays.asList(t) into new ArrayList<>(...) to allow its resizing. Arrays.asList is just a fixed size wrapper that doesn’t support adding elements.

JavaScript

Note that as another answer says, merge can be replaced with computeIfAbsent.

If you are into streams, you can use mutable reduction:

JavaScript
Advertisement