Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Map<String,String> to Map<String,Object>

I have Two Maps

Map<String, String> filterMap  Map<String, Object> filterMapObj 

What I need is I would like to convert that Map<String, String> to Map<String, Object>. Here I am using the code

        if (filterMap != null) {             for (Entry<String, String> entry : filterMap.entrySet()) {                 String key = entry.getKey();                 String value = entry.getValue();                 Object objectVal = (Object)value;                 filterMapObj.put(key, objectVal);             }         } 

It works fine, Is there any other ways by which I can do this without iterating through all the entries in the Map.

like image 399
arjuncc Avatar asked Jan 10 '14 06:01

arjuncc


People also ask

How do you turn a Map into an object?

To convert a Map to an object, call the Object. fromEntries() method passing it the Map as a parameter, e.g. const obj = Object. fromEntries(map) . The Object.

How do you convert a Map to a String?

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

Can we convert String to object in Java?

We can also convert the string to an object using the Class. forName() method. Parameter: This method accepts the parameter className which is the Class for which its instance is required.


Video Answer


1 Answers

Instead of writing your own loop that calls put, you can putAll, which does the same thing:

filterMapObj.putAll(filterMap); 

(See the Javadoc.)

And as Asanka Siriwardena points out in his/her answer, if your plan is to populate filterMapObj immediately after creating it, then you can use the constructor that does that automatically:

filterMapObj = new HashMap<>(filterMap); 

But to be clear, the above are more-or-less equivalent to iterating over the map's elements: it will make your code cleaner, but if your reason for not wanting to iterate over the elements is actually a performance concern (e.g., if your map is enormous), then it's not likely to help you. Another possibility is to write:

filterMapObj = Collections.<String, Object>unmodifiableMap(filterMap); 

which creates an unmodifiable "view" of filterMap. That's more restrictive, of course, in that it won't let you modify filterMapObj and filterMap independently. (filterMapObj can't be modified, and any modifications to filterMap will affect filterMapObj as well.)

like image 94
ruakh Avatar answered Oct 07 '22 08:10

ruakh