1

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.

2
  • Not clear on the problem you are trying to solve. Have you tried using a Map<String, String> and putting in the integers as Strings in the first place? Commented Feb 24, 2016 at 0:56
  • Put the Integer as String. Could also be helpful to create a function which can recognise if the String is also an Integer. Commented Feb 24, 2016 at 1:00

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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

I hope nobody puts a NotAString in that! If you go down this approach, why not just check if (String.class.equals(obj.getClass()) ?
@yshavit That's what he said that he needs to convert the Integers to String
My point was that just checking if the class name contains "String" is too broad. There are classes other than java.lang.String that match that.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.