如何转换Map< Object,Object>映射到< String,String>在java中? [英] How to convert Map<Object, Object> to Map<String, String> in java?
问题描述
我具有对象类型的Map,我需要将此映射转换为String类型.
I have the Map of type Object, i need to convert this map into the type String.
Map<String, String> map = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(instream);
任何机构都可以告诉我如何将属性分配给上方地图吗?
Can any body please tell me, how to assign the properties to above map?
感谢&问候, 姆斯奈杜
Thanks & Regards, Msnaidu
推荐答案
将属性添加到地图的最简单方法是(根据您的示例):
The cleanest way to add the properties to the map would be (following on from your example):
for (String propName : properties.stringPropertyNames()) {
map.put(propName, properties.getProperty(propName));
}
在这种特殊情况下,这很好用,因为Properties
对象确实是一个包含String键和值的映射,正如getProperty
方法清楚表明的那样.仅出于可怕的向后兼容性原因,才将其声明为Map<Object, Object>
.
This works nicely in this particular case, because the Properties
object is really a map containing String keys and values, as the getProperty
method makes clear. It's only declared as Map<Object, Object>
for horrible backwards-compatibility reasons.
通过使用特定于属性的方法,而不是将其仅视为Map<Object, Object>
,您可以使用完美的类型安全性(而不是强制转换)填充Map<String, String>
.
By using the Properties-specific methods, rather than treating this as just a Map<Object, Object>
, you can populate your Map<String, String>
with perfect type-safety (rather than having to cast).
这篇关于如何转换Map< Object,Object>映射到< String,String>在java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!