How can I convert Map<String,Object>
to Map<String,String>
?
This does not work:
Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String Map<String,String> newMap =new HashMap<String,String>(map);
Use Object#toString() . String string = map. toString();
In Java, you can use the Jackson library to convert a Java object into a Map easily.
Convert a Map to a String Using Java Streams To perform conversion using streams, we first need to create a stream out of the available Map keys. Second, we're mapping each key to a human-readable String.
Now that we have Java 8/streams, we can add one more possible answer to the list:
Assuming that each of the values actually are String
objects, the cast to String
should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.
Map<String,Object> map = new HashMap<>(); Map<String,String> newMap = map.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
If your Objects
are containing of Strings
only, then you can do it like this:
Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String Map<String,String> newMap =new HashMap<String,String>(); for (Map.Entry<String, Object> entry : map.entrySet()) { if(entry.getValue() instanceof String){ newMap.put(entry.getKey(), (String) entry.getValue()); } }
If every Objects
are not String
then you can replace (String) entry.getValue()
into entry.getValue().toString()
.
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