Map.of throws UnsupportedOperationException

Last modified date

Comments: 0

Error

When creating a new Map in Java using the Map.of operation, the exception UnsupportedOperationException is thrown when performing the remove() operation.

Reason

The Map.of function returns an immutable map, therefore the remove() operation is not allowed.

Solution

The solution is to use aHashMap, which is a mutable object, through either:

new HashMap<>(Map.of(...));

or the traditional way:

Map myMap = new HashMap<>();
myMap.put(..., ...);

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.