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()));
Answer from skeryl on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java collections › java map › converting map to map in java
Converting Map to Map in Java | Baeldung
January 8, 2024 - In this tutorial, we’ll discuss different approaches to solving the problem. Also, as we can see, although the type of MAP1 is Map<String, Object>, all entries’ values are strings.
Discussions

apex - How to convert Map<String,Object> into Map<string,string>()? - Salesforce Stack Exchange
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... strJSON= res.getBody(); system.debug('strJson>>>>>'+strJSON); Map mapJSON = (Map) JSON.deserializeUntyped(strJSON); Map mapLocalSemi = (Map More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
April 1, 2016
java - Converting Map<String,String> to Map<String,Object> - Stack Overflow
I have Two Maps Map filterMap Map filterMapObj What I need is I would like to convert that Map to Map . Here... More on stackoverflow.com
🌐 stackoverflow.com
Mapping a Bean to Map<String,Object>
Yep! Looking for some opportunities for mapping Object to EntityDTO or Map to EntityDTO. Otherwise I should create Entity layer, but I don't want to do that because I already have postman collection with description of data response. More on github.com
🌐 github.com
June 27, 2021
dictionary - How to convert Map<Object, Object> to Map<String, String> in java? - Stack Overflow
I have the Map of type Object, i need to convert this map into the type String. Map map = new HashMap (); Properties properties = new Properties(); More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 3
12

Well you can't safely cast it to a Map<String, String> because even though you know you've only got strings as the values, the compiler doesn't. That's like expecting:

Object x = "foo";
String y = x;

to work - it doesn't; you need to explicitly cast.

Likewise you can explicitly cast here, too, if you go via Object:

Map<String, Object> x = ...;
Map<String, String> y = (Map<String, String>) (Object) x;

Now you'll get a warning saying that it's an unchecked cast, because unlike the earlier "object to string" cast, there's no execution-time check that it's really valid. Type erasure means that a map doesn't really know its key/value types. So you end up with checking only being done when elements are fetched:

import java.util.*;

class Test {
    public static void main(String[] args) {
        Map<String, Object> x = new HashMap<>();
        x.put("foo", "bar");
        x.put("number", 0);
        Map<String, String> y = (Map<String, String>) (Object) x;
        // This is fine
        System.out.println(y.get("foo"));

        // This goes bang! It's trying to cast an Integer to a String
        System.out.println(y.get("number"));
    }
}

So if you really want to avoid creating a new map, this "cast via Object" will work - but it's far from ideal.

Your approach is safer, although you can make it slightly more efficient by avoiding the lookup:

public static Map<String, String> copyToStringValueMap(
        Map<String, Object> input) {
    Map<String, String> ret = new HashMap<>();
    for (Map.Entry<String, Object> entry : input.entrySet()) {
        ret.put(entry.getKey(), (String) entry.getValue());
    }
    return ret;
}
2 of 3
8

A Java 8 solution:

private Map<String, String> stringifyValues(Map<String, Object> variables) {
    return variables.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> (String) e.getValue()));
}
🌐
Coderanch
coderanch.com › t › 425284 › java › convert-hashmap-string-anytype-hashMap
convert hashmap <string, anytype > to hashMap<string, object> (Java in General forum at Coderanch)
Can somebody help me to convert any type of "values" , might be integer,string .. To object I want to keep the key as same and want to convert the value as object thanks zuje ... Anything that is not a primitive is already an Object. Therefore, Map<String,Integer> is a Map<? extends String,? extends Object>, and you can use it in the putAll method: Also, most Map implementation classes have a constructor that takes a Map<? extends K,? extends V> so it's even shorter for only one map:
🌐
GitHub
github.com › mapstruct › mapstruct › issues › 2504
Mapping a Bean to Map<String,Object> · Issue #2504 · mapstruct/mapstruct
June 27, 2021 - Sorry I was not clear enough. With Map<String, ?> I mean you to replace ? to the type you want. If you use Map<String, Object> you'll get compiler errors (from MapStruct) saying that it cannot map from Object to String and etc.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 38357378 › string-to-mapstring-object
java - String to Map<String,Object> - Stack Overflow
I have this string "{id={date=1467991309000, time=1467991309000, timestamp=1467991309, timeSecond=1467991309, inc=-360249353, machine=-705844029, new=false}, id_lista={date=1467991309000, time=
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-how-to-convert-a-map-string-object-to-map-string-string-in-java
Java: Converting Map<String, Object> to Map<String, String> - CodingTechRoom
Map<String, Object> map = new HashMap<>(); map.put("name", "John Doe"); map.put("age", 30); map.put("height", 175.5); map.put("isEmployed", true); Write a method to convert each entry from the original map to a string representation.
🌐
Salesforce
trailhead.salesforce.com › trailblazer-community › feed › 0D54S00000JyBZWSA3
what is (Map(String, Object>) | Salesforce Trailblazer Community
Skip to main content · The online Trailblazer Community becomes read-only Oct 30, 2026, as we move new community conversations to Slack. Read the FAQ
🌐
Baeldung
baeldung.com › home › java › java collections › java map › map to string conversion in java
Map to String Conversion in Java | Baeldung
January 8, 2026 - Let’s iterate over all the keys in our Map and, for each of them, append the key-value combination to our resulting StringBuilder object.
🌐
Baeldung
baeldung.com › home › java › java string › converting string or string array to map in java
Converting String or String Array to Map in Java | Baeldung
January 8, 2024 - In this method, we use StringTokenizer() to split the String by the delimiter (comma in this case) and then use split(“=”) to extract the key and value. The resulting key-value pairs are added to the Map.
🌐
Alex MacArthur
macarthur.me › posts › creating-a-map-method-for-objects-strings-sets-and-maps
Creating a .map() Method for Objects, Strings, Sets, and Maps | Alex MacArthur
March 4, 2023 - So overused. So 2013. But I’m choosing to submit to its applicability for this post. Now, we continue: This one’s a bit simpler than our Object map. Turn the target string into an array, map() over it as per usual, and turn it back into a string:
🌐
Reddit
reddit.com › r/learnprogramming › java streams - how to convert map > to map ?
r/learnprogramming on Reddit: Java Streams - how to convert Map <String, Optional<Object>> to Map <String, Object>?
August 25, 2022 -

Hi, the task is to assign every most populated city of each continent to its continent.

"countries" is the map type <String, Country> where String is the country code, and value is just the Country object assigned to that code.

same with "cities", but it's map type <Integer, City> where Integer is ID of the assigned city

The implementation I've made almost provides the solution but it's a map of <String, Optional<City>> instead of <String, City> (where String is the continent, and City is the most populated city)

How to convert the map values of type <Optional<City>> to type <City>?

Map<String, Optional<City>> ex = cities.values().stream()
         .collect(Collectors.
          groupingBy(p -> countries.get(p.getCountryCode()).getContinent(),       
                 Collectors.maxBy(Comparator.comparing(City::getPopulation))));

Also the github with exercises and provided data: https://github.com/deepcloudlabs/stream-api-exercises-part1

City class: https://github.com/deepcloudlabs/stream-api-exercises-part1/blob/master/src/com/example/domain/City.java

Country class: https://github.com/deepcloudlabs/stream-api-exercises-part1/blob/master/src/com/example/domain/Country.java

🌐
Medium
medium.com › code-science › convert-java-object-to-map-edfb9080834d
Convert Java Object to Map. Scenario | by Ishaan Gupta | Code Science | Medium
May 5, 2023 - class Main { public static void main(String[] args){ Employee emp = new Employee(); emp.setName("ABC"); emp.setAge(30); emp.setSkillts(Arrays.asList("hello", "there")); // object --> map Map<String, Object> objectMap = FooBar.convertObjectToMap(emp); System.out.println(obejctMap); } } { name : "ABC", age : 30, skills : [ "hello", "there" ] } You can create a generic function which can convert any object to a map ·