Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Map<String,Object> to Map<String,String>

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); 
like image 675
Mawia Avatar asked May 29 '13 06:05

Mawia


People also ask

How do you convert a Map to a String?

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

Can we convert object to Map?

In Java, you can use the Jackson library to convert a Java object into a Map easily.

How do you convert a Map key and value in a String?

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.


2 Answers

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())); 
like image 76
skeryl Avatar answered Oct 03 '22 15:10

skeryl


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().

like image 34
Shreyos Adikari Avatar answered Oct 03 '22 15:10

Shreyos Adikari