How can I convert Map
to Map
?
This does not work:
Map map = ne
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()));
The following will transform your existing entries.
TransformedMap.decorateTransform(params, keyTransformer, valueTransformer)
Where as
MapUtils.transformedMap(java.util.Map map, keyTransformer, valueTransformer)
only transforms new entries into your map
Great solutions here, just one more option that taking into consideration handling of null
values:
Map<String,Object> map = new HashMap<>();
Map<String,String> stringifiedMap = map.entrySet().stream()
.filter(m -> m.getKey() != null && m.getValue() !=null)
.collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
There are two ways to do this. One is very simple but unsafe:
Map<String, Object> map = new HashMap<String, Object>();
Map<String, String> newMap = new HashMap<String, String>((Map)map); // unchecked warning
The other way has no compiler warnings and ensures type safety at runtime, which is more robust. (After all, you can't guarantee the original map contains only String values, otherwise why wouldn't it be Map<String, String>
in the first place?)
Map<String, Object> map = new HashMap<String, Object>();
Map<String, String> newMap = new HashMap<String, String>();
@SuppressWarnings("unchecked") Map<String, Object> intermediate =
(Map)Collections.checkedMap(newMap, String.class, String.class);
intermediate.putAll(map);
Not possible.
This a little counter-intuitive.
You're encountering the "Apple is-a fruit" but "Every Fruit is not an Apple"
Go for creating a new map and checking with instance of with String