10 java hashmap system-properties
这篇好文章向我们展示了如何将所有当前系统属性打印到STDOUT,但我需要将所有内容转换System.getProperties()为a HashMap<String,String>.
因此,如果有一个名为"baconator"的系统属性,其值为"yes!",我设置System.setProperty("baconator, "yes!"),那么我希望HashMap有一个键baconator和一个相应的值yes!,等等.所有系统属性的相同想法.
我试过这个:
Properties systemProperties = System.getProperties();
for(String propertyName : systemProperties.keySet())
;
Run Code Online (Sandbox Code Playgroud)
但后来得到一个错误:
类型不匹配:无法从元素类型Object转换为String
那么我试过:
Properties systemProperties = System.getProperties();
for(String propertyName : (String)systemProperties.keySet())
;
Run Code Online (Sandbox Code Playgroud)
我收到这个错误:
只能遍历数组或java.lang.Iterable的实例
有任何想法吗?
我做了一个样本测试 Map.Entry
Properties systemProperties = System.getProperties();
for(Entry<Object, Object> x : systemProperties.entrySet()) {
System.out.println(x.getKey() + " " + x.getValue());
}
Run Code Online (Sandbox Code Playgroud)
对于您的情况,您可以使用它来存储在您的Map<String, String>:
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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10983 次 |
| 最近记录: |