【问题标题】:How to convert all Java System Properties to HashMap<String,String>?如何将所有 Java 系统属性转换为 HashMap<String,String>?
【发布时间】:2013-06-24 06:27:57
【问题描述】:

这个nice article 向我们展示了如何将所有当前系统属性打印到STDOUT,但我需要将System.getProperties() 中的所有内容转换为HashMap&lt;String,String&gt;

因此,如果有一个名为“baconator”的系统属性,其值为“yes!”,我使用System.setProperty("baconator, "yes!") 设置,那么我希望HashMap 具有baconator 的键和相应的键yes! 的值等。所有系统属性的想法相同。

我试过了:

Properties systemProperties = System.getProperties();
for(String propertyName : systemProperties.keySet())
    ;

然后得到一个错误:

类型不匹配:无法从元素类型 Object 转换为 String

然后我尝试了:

Properties systemProperties = System.getProperties();
for(String propertyName : (String)systemProperties.keySet())
    ;

我得到了这个错误:

只能遍历数组或 java.lang.Iterable 的实例

有什么想法吗?

【问题讨论】:

标签: java hashmap system-properties


【解决方案1】:

我使用Map.Entry做了一个样本测试

Properties systemProperties = System.getProperties();
for(Entry<Object, Object> x : systemProperties.entrySet()) {
    System.out.println(x.getKey() + " " + x.getValue());
}

对于您的情况,您可以使用它来将其存储在您的Map&lt;String, String&gt;

Map<String, String> mapProperties = new HashMap<String, String>();
Properties systemProperties = System.getProperties();
for(Entry<Object, Object> x : systemProperties.entrySet()) {
    mapProperties.put((String)x.getKey(), (String)x.getValue());
}

for(Entry<String, String> x : mapProperties.entrySet()) {
    System.out.println(x.getKey() + " " + x.getValue());
}

【讨论】:

    【解决方案2】:

    循环通过stringPropertyNames() 方法返回的Set&lt;String&gt;(即Iterable)。处理每个属性名时,使用getProperty获取属性值。然后您将put您的属性值所需的信息转换为您的HashMap

    【讨论】:

      【解决方案3】:

      从 Java 8 开始,您可以键入这个 - 相当长的 - one-liner:

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

      【讨论】:

        【解决方案4】:

        这确实有效

        Properties properties= System.getProperties();
        for (Object key : properties.keySet()) {
            Object value= properties.get(key);
        
            String stringKey= (String)key;
            String stringValue= (String)value;
        
            //just put it in a map: map.put(stringKey, stringValue);
            System.out.println(stringKey + " " + stringValue);
        }
        

        【讨论】:

          【解决方案5】:

          您可以使用Properties 中的entrySet() 方法从Properties(即Iterable)中获取Entry 类型,或者您可以使用Properties 类中的stringPropertyNames() 方法来获取Set 此属性列表中的键。使用getProperty方法获取属性值。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-02-03
            • 1970-01-01
            • 1970-01-01
            • 2013-06-17
            • 2016-06-27
            • 2014-09-27
            • 2014-07-20
            • 2017-06-17
            相关资源
            最近更新 更多