How can I cast a Map<Object,Object>
to Map<String,String>
in the cleanest way?
Is there a way to do that without iterating over the map?
Thanks
In general, you cannot typecast a Map to a HashMap without risk of a class-cast exception. If the Map is a TreeMap then the cast will (and must) fail. You can avoid the exception by making using instanceof to check the type before you cast, but if the test says "not a HashMap" you are stuck.
Use Object#toString() . String string = map. toString();
To convert an object to a Map , call the Object. entries() method to get an array of key-value pairs and pass the result to the Map() constructor, e.g. const map = new Map(Object. entries(obj)) . The new Map will contain all of the object's key-value pairs.
The actual answer is:
Map<Object,Object> valueMap = ...;
@SuppressWarnings("unchecked")
Map<String,String> targetMap = (Map)valueMap;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With