If I have a HashMap<String,Object> that has three entries that are <String,String> and one that is <String,Integer> is there a way to "cast" this into a HashMap<String,String> easily? Right now I and making a new HashMap and copying all of the values over so that I can convert the Integer during the copying.
4 Answers
Should be able to cast it, but expect an exception when trying to retrieve one of the integers out of the map.
What I think you're asking is to cast the content of the hashmap, in this case the values, so they all come out as strings, and that's not going to happen.
Best solution is to convert the integer into a string when populating the map in the first place.
Comments
You can cast the original map, no need to copy:
map.put("intKey", map.get("intKey").toString());
Map<String, String> fixedMap = (Map) map;
It does look like something is wrong with your design though. It would be better to fix the code that shoves the integer into the map to begin with, so that you would not need to deal with this trickery downstream.
Comments
Something like this should be easier:
Class<? extends Object> className = obj.getClass();
if (className.getName().contains("String")){
//add the object
}else {
//convert it to String and then add to HashMap
}
3 Comments
NotAString in that! If you go down this approach, why not just check if (String.class.equals(obj.getClass()) ?If you're using java 8, you can use forEach with BiConsumer.
Take a look in the code below
Map<String, Object> map = new HashMap<>();
map.put("a", "a");
map.put("b", "b");
map.put("1", Integer.valueOf(1));
map.forEach((k, v) -> map.put(k, v.toString()));
After line map.forEach((k, v) -> map.put(k, v.toString())); all values in the map are Strings. Of courste that loop is still there, but you are using a language feature/resource.
IntegerasString. Could also be helpful to create a function which can recognise if the String is also an Integer.