简体   繁体   English

将整数转换为字符串,对象哈希图中的字符串

[英]Converting integers to strings in a String, Object hashmap

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? 如果我有一个HashMap<String,Object> ,其中有三个条目,分别为<String,String> ,一个是<String,Integer>是否可以轻松地将其“投射”到HashMap<String,String> 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. 现在,我创建一个新的HashMap并复制所有值,以便在复制过程中可以转换Integer。

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. 最好的解决方案是,首先填充地图时将整数转换为字符串。

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. 最好修复将整数推入映射表的代码,这样您就无需在下游处理这种棘手的问题。

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
  }

If you're using java 8, you can use forEach with BiConsumer. 如果您使用的是Java 8,则可以将forEach与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())); 在行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. 当然,该循环仍然存在,但是您正在使用语言功能/资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM