Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Cast a Map

Tags:

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

like image 797
Mark Avatar asked Oct 16 '11 23:10

Mark


People also ask

Can you cast Map to HashMap?

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.

How do you convert a Map to a string?

Use Object#toString() . String string = map. toString();

Can object convert to Map?

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.


1 Answers

The actual answer is:

Map<Object,Object> valueMap = ...;
@SuppressWarnings("unchecked")
Map<String,String> targetMap = (Map)valueMap;
like image 155
Chris J Avatar answered Sep 17 '22 14:09

Chris J