Java – easily convert maps to maps

The API I am using has a method to return map < string, Object >, but I know that in this case, object is string, so I want to use it as map < string, string >

But for some reason, I can't just use it. Java says that map < string, Object > for some reason, it can't be converted into map < string, string >

I used:

Map<String,Object> tempMap = someApiMethodReturningAMap();
Map<String,String> map = new HashMap<String,String>();
for (String i : tempMap.keySet()) {
    map.put(i,String.valueOf(tempMap.get(i)));
}

As a solution, but is there a simpler way?

Solution

Then you can't safely convert it to map < string, string >, because even if you know that you only have string as value, the compiler won't It's like looking forward to:

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

Work – it does not; You need to cast it explicitly

Similarly, if you use object, you can also explicitly convert here:

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

Now you will get a warning that it is an unchecked cast, because unlike the previous "object to string" cast, it does not check whether it is really valid when executed Type erasure means that the map does not really know its key / value type Therefore, in the end, only check whether it is completed when getting the element:

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>) (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 through object" will work - but it's far from ideal

Your approach is safer, but you can improve efficiency by avoiding lookups:

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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>