An API I am using has a method that returns a Map<String, Object>, but I know the Object's are String's in this case, so I want it as a Map<String, String>.
But for some reason I can't just cast it, Java says Map<String, Object> cannot be casted to Map<String, String>, for some reason.
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 workaround, but is there an easier way?
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;
}
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()));
}
Good solutions here, but I want to add another one that taking into consideration handling 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()));
Related
I have a Map object stored in a sessionScope. If I cast it to the following object:
Map<String,Object> mapItem = (Map<String, Object>) entry.getValue();
I get a Type safety warning. Type safety:
Unchecked cast from Object to Map<String,Object>
I tried to cast the scope variable to an object and check what instance the object is but then I can not directly check if it is of Map<String,Object>. So I wonder how I should handle this further?
Object obj = entry.getValue();
if(obj instanceof Map<?, ?>) {
//not sure what to do here
}
Any help is highly appreciated!
I think the issue is with the generics applied to the original Map your Entry is from. Consider these examples
Map<String, Object> map = new HashMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Map<String, Object> mapItem = (Map<String, Object>) entry.getValue(); // Will have unchecked warning
}
// Declare another map specifying the values type more specifically
Map<String, Map<String, Object>> map2 = new HashMap<>();
for (Map.Entry<String, Map<String, Object>> entry : map2.entrySet()) {
Map<String, Object> mapItem = entry.getValue(); // Will not require cast
}
The issue occurs because the compiler doesn't know anything more about the values type than its an Object. You know its a Map<String, Object> so you can tell the compiler that with generics and it will enforce that in the rest of the code.
It's not easy to achieve that;
Look at how to handle it in Gson:
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
new Gson().fromJson("{}", mapType);
I have an Object which is of type Map<String, String> which has few entries. I expected to get a ClassCastException while casting this object to Map<String, Integer>. But the cast was successful. Why is it that this did not throw any exception?
Map<String, String> map1 = new HashMap<>();
map1.put("key1", "value1");
map1.put("key2", "value2");
Object o = map1;
Map<String, Integer> map2 = (Map<String, Integer>) o;
Edit: Casting from o not map1.
Generic-checking is made at compile time,while casting checking is done at the time of running the program.So You had got casting exception at run time.
You parse it as Integer.parseInt(String) and put the value into map2.
Are you sure that's right?
Your example fails to compile:
Error:(21, 60) java: incompatible types: java.util.Map<java.lang.String,java.lang.String> cannot be converted to java.util.Map<java.lang.String,java.lang.Integer>
However, changing from map1 to o, does compile:
//...
Object o = map1;
Map<String, Integer> map2 = (Map<String, Integer>) o;
Perhaps you're looking for something like this?
Map<String, String> map1 = new HashMap<>();
map1.put("key1", "1");
map1.put("key2", "2");
Map<String, Integer> map2 = new HashMap<>();
map1.forEach((key,value) -> map2.put(key, Integer.parseInt(value)));
Why does this cast work?
import java.util.HashMap;
import java.util.Map;
public class TestMap {
public static void main(String[] args) {
Map<String, Map<String, Map<String, Map<String,Integer>>>> resultMap = new HashMap<>();
Map<String, Object> aMap = new HashMap<String, Object>();
Map<String, Integer> hiddenMap = new HashMap<String, Integer>();
hiddenMap.put("fortytwo", 42);
aMap.put("key", hiddenMap);
resultMap = (Map<String, Map<String, Map<String, Map<String, Integer>>>>) aMap.get("key");
System.out.println(resultMap);
}
}
also this:
Map<String, Map<String, Map<String, Map<String,Map<String,Integer>>>>> resultMap = new HashMap<>();
...
resultMap = (Map<String, Map<String, Map<String, Map<String,Map<String,Integer>>>>>) aMap.get("key");
and so on...
How does this happen that the hidden map which is Map<String, Integer> gets successfully cast to Map<String, Map<String, Map<String, Map<String,Integer>>>> resultMap?
Always prints:
{fortytwo=42}
Also this works (Map instead of Map):
public static void main(String[] args) {
Map<String, Map<String, Map<String, Map<String,Map<String,Integer>>>>> resultMap = new HashMap<>();
Map<String, Map> aMap = new HashMap<String, Map>();
Map<String, Integer> hiddenMap = new HashMap<String, Integer>();
hiddenMap.put("fortytwo", 42);
aMap.put("key", hiddenMap);
resultMap = (Map<String, Map<String, Map<String, Map<String,Map<String,Integer>>>>>) aMap.get("key");
System.out.println(resultMap);
}
EDIT: So as #shizhz says, it is because of Type Erasure of course! So the code above is equivalent to:
Map resultMap = new HashMap();
Map aMap = new HashMap();
Map hiddenMap = new HashMap();
hiddenMap.put("fortytwo", 42);
aMap.put("key", hiddenMap);
resultMap = (Map) aMap.get("key");
Which also works
Because java generics is used at compile time to provide tighter type checks, the type parameter is erased by compiler according Type Erasure rules:
Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
Insert type casts if necessary to preserve type safety.
Generate bridge methods to preserve polymorphism in extended generic types.
In code Map<String, Map> aMap = new HashMap<String, Map>();, the value in aMap is a raw type Map, which means the compiler has no idea what's the type it contains, when you try to cast a raw type of Map to any generics type of Map like Map<String, Integer>, the best compiler can do is giving you a warning. The generic type is erased at compile time and type cast will be generated when you get value from a generic map, so you can only get a runtime ClassCastException exception if the type mismatchs.
Let's have a look at the following example:
public static void main(String[] args) {
Map map = new HashMap();
map.put("hello", "world");
map.put(new Integer(1), 1);
map.put(new Object(), Lists.newArrayList("hello"));
Map<String, Integer> m = (Map<String, Integer>) map;
System.out.println(m);
Integer i = m.get("hello");// ClassCastException happens at here at runtime
}
I'm trying to convert a Map containing all kinds of keys and values to Map<String, Integer> but there's no compile error, after type erasure, the above code is actually equivalent to:
public static void main(String[] args) {
Map map = new HashMap();
map.put("hello", "world");
map.put(new Integer(1), 1);
map.put(new Object(), Lists.newArrayList("hello"));
Map m = (Map) map;
System.out.println(m);
Integer i = (Integer)m.get("hello");
}
Now you can easily tell why the last line caused ClassCastException.
Since you've declared aMap as Map<String, Object>, the compiler cannot tell if the values won't indeed be of type Map<String, Map<String, Map<String,Integer>>>. It will just give you an "Unchecked cast" warning to let you think about the consequences.
The cast works unless you're actually trying to do something with the values:
resultMap.get("fortytwo").isEmpty();
will result in
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.util.Map
If you had declared aMap as Map<String, Map<String, Map<String, Map<String, Map<String, Integer>>>>> you wouldn't be able to put hiddenMap in it in the first place.
I am new in java generics and facing following issues.
I have have method like,
private static void fillDescriptiveData(HashMap<String, Object> output, String attributeMapping) {
for (Map.Entry<String, Object> outputInEntry : output.entrySet()) {
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue(outputValue);
}
}
Now if I call API as below way
HashMap<String, Object> ObjectMap = new HashMap<String, Object>();
HashMap<String, List> listMap = new HashMap<String, List>();
fillDescriptiveData(ObjectMap,"here");
this one working fine.
fillDescriptiveData(listMap,"here");
this call gives error
The method fillDescriptiveData(HashMap, String) in the type CustomAttribute is not applicable for the arguments (HashMap, String)`
why ?
In row to solve this issue I encounter with one more issue,
private static void fillDescriptiveData(HashMap<String, ? extends Object> output, String attributeMapping) {
for (Map.Entry<String, ? extends Object> outputInEntry : output.entrySet()) {
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue(outputValue); /* Error comes at this line */
}
}
HashMap<String, ? extends Object> ObjectMap = new HashMap<String, Object>();
HashMap<String, List> listMap = new HashMap<String, List>();
fillDescriptiveData(ObjectMap,"here");
fillDescriptiveData(listMap,"here");
error at line - outputInEntry.setValue(outputValue);
The method setValue(capture#4-of ? extends Object) in the type
Map.Entry is not applicable for
the arguments (String)
why ?
What is the best way to avoid this issues ?
This is the case when you could use type variables:
private static <T> void fillDescriptiveData(Map<String, T> output,String attributeMapping)
{
for(Map.Entry<String, T> outputInEntry : output.entrySet())
{
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue((T) outputValue);
}
}
More specifically, your second type-parameter in the map is unbounded. Object will not work here as it is specific class. ? extends Object is somewhat nonsense.
Just HashMap<String, ?> would work until you will just read the map, but you will not be able to put something here. So only one way - using type variable.
EDIT: One more thing: please, use interfaces where it's possible. So here instead of HashMap<String, T> better use Map<String, T>. It isn't a mistake, just good and proper style of code.
The error with this line:
outputInEntry.setValue(outputValue);
Is that you're always putting a string into the entry. This will only work if the entry is of type ? super String, or exactly String. So it will not work for a Map<String, Object> or Map<String, List>.
It seems like you just want to map each value to a string. You can do it, but to be type safe, you need to create a new Map<String, String>. Since you're always mapping to a String.
If you for instance pass in a Map<String, List<?>> and (unsafely) replace all the values with strings. Someone could still keep using the Map<String, List<?>> that was passed into the function, but it now contains strings as values instead of lists. When they try to retrieve a List from it they get a class cast exception.
Something like this:
private static Map<String, String> fillDescriptiveData(HashMap<String, ?> input,
String attributeMapping) {
Map<String, String> output = new HashMap<>();
for(Entry<String, ?> e : input.entrySet()) {
String outputKey = e.getKey();
String outputValue = e.getValue().toString();
outputValue
= getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
output.put(outputKey, outputValue);
}
return output;
}
Map<String, String> r1 = fillDescriptiveData(ObjectMap, "here");
Map<String, String> r2 = fillDescriptiveData(listMap, "here");
I'm new to Java, but not new to programming, so as my first project I decided to create a .txt-.csv parser for someone at work. I read each line in the .txt file and separate it into separate Maps for sections, subsections, subsubsections, and the subsubsections' contents. Each Map is then assigned to the Map above it (more on this below). I print everything to it just fine, but when I try to read it I get the following error: "java.lang.String cannot be cast to java.util.Map". The error only appears after the code is run, not while compiling, nor in NetBeans IDE.
My Maps are in the following form with each Object being the Map below it: (Why can't Java make this easy -_- Associative Arrays are all I want)
(Map)array=<string,Object>
(Map)subarray=<String,Object>
(Map)subsubarray=<String,Object>
(Map)subsubcontents=<String,String>
May not be the most efficient way to read this, plan on converting this to recursive function later, but here is my code, copy-pasted from my project. I put comments at where I've found the error to be.
public static Map<String,Object> array=new HashMap<String,Object>();
/* Code for populating the following Maps and pushing them into array
<String,Object>subarray
<String,Object>subsubarray
<String,String>subsubcontents
*/
Set section=array.entrySet();
Iterator sectionI=section.iterator();
while(sectionI.hasNext()) {
Map.Entry sectionInfo=(Map.Entry)sectionI.next();
Map<String,Object> subMap=(Map)sectionInfo.getValue();
Set subSet=subMap.entrySet();
Iterator subI=subSet.iterator();
while(subI.hasNext()) {
Map.Entry subInfo=(Map.Entry)subI.next();
Map<String,Object> subsubMap=(Map)subInfo.getValue();
Set subsubSet=subsubMap.entrySet();
Iterator subsubI=subsubSet.iterator();
while(subsubI.hasNext()) {
System.out.println("test");
Map.Entry subsubInfo=(Map.Entry)subsubI.next();
Map<String,Object> subcontentsMap=(Map)subsubInfo.getValue();
/*
The above line seems to be causing the issues.
If you comment out the rest of this loop (below this comment)
the error will still appear. If you comment out the rest of this loop
(including the line above this comment) it disappears.
Power of deduction my dear Watson.
*/
Set subcontentsSet=subcontentsMap.entrySet();
Iterator keys=subcontentsSet.iterator();
while(keys.hasNext()) {
Map.Entry keyMap=(Map.Entry)keys.next();
}
Iterator values=subcontentsSet.iterator();
while(values.hasNext()) {
Map.Entry valueMap=(Map.Entry)values.next();
}
}
}
}
Any help would be much appreciated. I've been struggling with this for a couple of days now.
I think you need to clean up your generics to start with:
Set<Map.Entry<String, Object>> section = array.entrySet();
Iterator<Map.Entry<String, Object>> sectionI = section.iterator();
while (sectionI.hasNext()) {
Map.Entry<String, Object> sectionInfo = sectionI.next();
Map<String, Object> subMap = (Map<String, Object>) sectionInfo.getValue(); // is this actually a Map<String, Object>?
Set<Map.Entry<String, Object>> subSet = subMap.entrySet();
Iterator<Map.Entry<String, Object>> subI = subSet.iterator();
while (subI.hasNext()) {
Map.Entry<String, Object> subInfo = subI.next();
Map<String, Object> subsubMap = (Map<String, Object>) subInfo.getValue(); // is this actually a Map<String, Object>?
Set<Map.Entry<String, Object>> subsubSet = subsubMap.entrySet();
Iterator<Map.Entry<String, Object>> subsubI = subsubSet.iterator();
while (subsubI.hasNext()) {
System.out.println("test");
Map.Entry<String, Object> subsubInfo = subsubI.next();
Map<String, Object> subcontentsMap = (Map<String, Object>) subsubInfo.getValue(); // somehow a String got in here?
/*
The above line seems to be causing the issues.
If you comment out the rest of this loop (below this comment)
the error will still appear. If you comment out the rest of this loop
(including the line above this comment) it disappears.
Power of deduction my dear Watson.
*/
Set<Map.Entry<String, Object>> subcontentsSet = subcontentsMap.entrySet();
Iterator<Map.Entry<String, Object>> keys = subcontentsSet.iterator();
while (keys.hasNext()) {
Map.Entry<String, Object> keyMap = keys.next();
}
Iterator<Map.Entry<String, Object>> values = subcontentsSet.iterator();
while (values.hasNext()) {
Map.Entry<String, Object> valueMap = values.next();
}
}
}
}
Then, you should be more explicit with your declaration of array:
public static Map<String, Map<String, Map<String, Map<String, String>>>> array = new HashMap<String, Map<String, Map<String, Map<String, String>>>>();
This would ensure that you are putting the correct objects into each of the maps. You will never be able to put a String value where a Map<> is expected because it will not compile. This will allow you to write the following code (without needing casts):
final Set<Map.Entry<String, Map<String, Map<String, Map<String, String>>>>> section = array.entrySet();
final Iterator<Map.Entry<String, Map<String, Map<String, Map<String, String>>>>> sectionI = section.iterator();
while (sectionI.hasNext()) {
final Entry<String, Map<String, Map<String, Map<String, String>>>> sectionInfo = sectionI.next();
final Map<String, Map<String, Map<String, String>>> subMap = sectionInfo.getValue();
final Set<Map.Entry<String, Map<String, Map<String, String>>>> subSet = subMap.entrySet();
final Iterator<Map.Entry<String, Map<String, Map<String, String>>>> subI = subSet.iterator();
while (subI.hasNext()) {
final Map.Entry<String, Map<String, Map<String, String>>> subInfo = subI.next();
final Map<String, Map<String, String>> subsubMap = subInfo.getValue();
final Set<Map.Entry<String, Map<String, String>>> subsubSet = subsubMap.entrySet();
final Iterator<Map.Entry<String, Map<String, String>>> subsubI = subsubSet.iterator();
while (subsubI.hasNext()) {
System.out.println("test");
final Map.Entry<String, Map<String, String>> subsubInfo = subsubI.next();
final Map<String, String> subcontentsMap = subsubInfo.getValue();
final Set<Map.Entry<String, String>> subcontentsSet = subcontentsMap.entrySet();
final Iterator<Map.Entry<String, String>> entries = subcontentsSet.iterator();
while (entries.hasNext()) {
final Map.Entry<String, String> entry = entries.next();
}
}
}
}
All that being said, all of those nested generics look ugly. I'd recommend you create some objects to represent your data.
You can do this :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement element = gson.fromJson (jsonString, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
Map<String,Object> resultMap = new Gson().fromJson(jsonObj, Map.class);
The exception tells you everything. This call subsubInfo.getValue(); is actually returning a String, not a Map, so you have a logical error when creating your maps.
The compiler will warn you about this if you change your declarations to Map<String, Map> instead of Map<String, Object>