【问题标题】:How to convert Map<Object, Object> to Map<String, String> in java?如何在 java 中将 Map<Object, Object> 转换为 Map<String, String>?
【发布时间】:2013-06-16 23:56:12
【问题描述】:

我有 Object 类型的 Map,我需要将此映射转换为 String 类型。

Map<String, String> map = new HashMap<String, String>();    
Properties properties = new Properties();    
properties.load(instream);     

谁能告诉我,如何将属性分配给上面的地图?

感谢和问候, 姆奈杜

【问题讨论】:

标签: java map inputstream


【解决方案1】:

加上Java 8Streams,我建议你使用Steam提供的API

在这里,我们假设每个值实际上都是 String 对象,转换为 String 应该是安全的:

Map<String,Object> map = new HashMap<>();

Map<String,String> stringifiedMapSafe = map.entrySet().stream()
     .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

现在,如果我们不确定所有元素都是String,我们想用null 过滤键/值:

Map<String,Object> map = new HashMap<>();

Map<String,String> stringifiedMapNotSafe = map.entrySet().stream()
             .filter(m -> m.getKey() != null && m.getValue() !=null)
             .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

【讨论】:

    【解决方案2】:

    遍历 Map Object,取 k v,将它们变成字符串并将其放入 Map String。

    Map<Object,Object> map1; // with object k,v
    Map<String, String> mapString = new HashMap<String, String>();
    for (Object key : map1.keySet()) {
                    String k = key.toString();
                    String v = mmap1.get(key).toString();
                    mapString.put(k, v);
                }
    

    【讨论】:

      【解决方案3】:

      将属性添加到地图的最简洁方法是(按照您的示例):

      for (String propName : properties.stringPropertyNames()) {
          map.put(propName, properties.getProperty(propName));
      }
      

      这在这种特殊情况下工作得很好,因为Properties 对象实际上是一个包含字符串键和值的映射,正如getProperty 方法所表明的那样。仅出于可怕的向后兼容性原因将其声明为 Map&lt;Object, Object&gt;

      通过使用特定于属性的方法,而不是将其视为 Map&lt;Object, Object&gt;,您可以使用完美的类型安全(而不是强制转换)填充您的 Map&lt;String, String&gt;

      【讨论】:

      【解决方案4】:
      Map<String, String> properties2Map(Properties p) {
                  Map<String, String> map = new HashMap<String, String>();
                  for(Map.Entry<Object, Object> entry : p.entrySet()) {
                      String key = (String) entry.getKey(); //not really unsafe, since you just loaded the properties
                      map.put(key, p.getProperty(key));
                  }
                  return map;
      }
      

      我还喜欢使用带有类型参数的实用方法来绕过泛型类型不变性并进行一些“向下转换”或“向上转换”(当我知道这样做是安全的时)。在这种情况下:

      @SuppressWarnings("unchecked")
      <A, B extends A> Map<B, B> downCastMap(Map<A,A> map) {
          return (Map<B, B>)map;
      }
      

      那你就可以写了

      Properties p = ...
      Map<String, String> map = downCastMap(p);
      

      【讨论】:

      • 我可以把它像 Map map = (Map) properties;
      • 是的,禁止原始类型并且未选中。但是,实用程序方法为阅读代码的其他人(和您自己)提供了更多的代码文档。
      【解决方案5】:

      可以直接转换:

      Properties properties = new Properties();
      Map<String, String> map = new HashMap<String, String>((Map)properties);
      

      【讨论】:

        【解决方案6】:

        因为我们知道 Properties 已经是一个字符串到字符串的映射,所以使用 rawtype 和未经检查的转换来做这件事是省事的。只需发表评论:

            Properties properties = new Properties();    
            properties.load(instream); 
        
            @SuppressWarnings({ "rawtypes", "unchecked" })
            // this is save because Properties have a String to String mapping
            Map<String, String> map = new HashMap(properties);
        

        【讨论】:

        • 是的,但是为什么要在进程中新建一个HashMap实例呢?
        • 因为我们不能更改cast属性实例为Map&lt;String, String&gt;类型,因为它实现了接口Map&lt;Object, Object&gt;
        • 看看我上面的答案和 cmets。
        【解决方案7】:
        Map<String,String> getPropInMap(Properties prop){       
            Map<String, String> myMap = new HashMap<String, String>();
            for (Object key : prop .keySet()) {
                myMap.put(key.toString(), prop .get(key).toString());
            }       
            return myMap;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-24
          • 2014-01-29
          • 2015-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-17
          相关资源
          最近更新 更多