如何将所有Java系统属性转换为HashMap<;字符串,字符串>;?
这向我们展示了如何将所有当前系统属性打印到STDOUT,但我需要将如何将所有Java系统属性转换为HashMap<;字符串,字符串>;?,java,hashmap,system-properties,Java,Hashmap,System Properties,这向我们展示了如何将所有当前系统属性打印到STDOUT,但我需要将system.getProperties()中的所有内容转换为HashMap 因此,如果有一个名为“baconator”的系统属性,其值为“yes!”,我用system.setProperty(“baconator,yes!”)设置,那么我希望HashMap有一个baconator键和相应的yes!值,等等。对于所有系统属性都有相同的想法 我试过这个: Properties systemProperties = System.ge
system.getProperties()
中的所有内容转换为HashMap
因此,如果有一个名为“baconator”的系统属性,其值为“yes!”,我用system.setProperty(“baconator,yes!”)
设置,那么我希望HashMap
有一个baconator
键和相应的yes!
值,等等。对于所有系统属性都有相同的想法
我试过这个:
Properties systemProperties = System.getProperties();
for(String propertyName : systemProperties.keySet())
;
但随后会出现一个错误:
类型不匹配:无法从元素类型对象转换为字符串
于是我试着:
Properties systemProperties = System.getProperties();
for(String propertyName : (String)systemProperties.keySet())
;
我得到了这个错误:
只能迭代java.lang.Iterable的数组或实例
有什么想法吗?我用
Map.Entry
Properties systemProperties = System.getProperties();
for(Entry<Object, Object> x : systemProperties.entrySet()) {
System.out.println(x.getKey() + " " + x.getValue());
}
Properties systemProperties=System.getProperties();
对于(条目x:systemProperties.entrySet()){
System.out.println(x.getKey()+“”+x.getValue());
}
对于您的情况,您可以使用它将其存储在地图中
:
Map-mapProperties=newhashmap();
Properties systemProperties=System.getProperties();
对于(条目x:systemProperties.entrySet()){
put((String)x.getKey(),(String)x.getValue());
}
对于(条目x:mapProperties.entrySet()){
System.out.println(x.getKey()+“”+x.getValue());
}
循环该方法返回的集合(它是Iterable
)。处理每个属性名称时,使用获取属性值。然后,您就有了将属性值放入哈希映射中所需的信息。这是行得通的
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);
}
您可以使用Properties
中的entrySet()
方法从Properties
获取Iterable
中的Entry
类型,也可以使用stringPropertyNames()
方法从Properties
类中获取此属性列表中键的集。使用getProperty
方法获取属性值。自Java 8以来,您可以键入一行相当长的命令:
Map<String, String> map = System.getProperties().entrySet().stream()
.collect(Collectors.toMap(e -> (String) e.getKey(), e -> (String) e.getValue()));
Map Map=System.getProperties().entrySet().stream()
.collect(Collectors.toMap(e->(String)e.getKey(),e->(String)e.getValue());
这是一份
Map<String, String> map = System.getProperties().entrySet().stream()
.collect(Collectors.toMap(e -> (String) e.getKey(), e -> (String) e.getValue()));