How to convert all Java System Properties to HashMap<String,String>?
Solution 1
I did a sample test using Map.Entry
Properties systemProperties = System.getProperties();
for(Entry<Object, Object> x : systemProperties.entrySet()) {
System.out.println(x.getKey() + " " + x.getValue());
}
For your case, you can use this to store it in your 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());
}
Solution 2
Since Java 8, you can type this -rather long- one-liner:
Map<String, String> map = System.getProperties().entrySet().stream()
.collect(Collectors.toMap(e -> (String) e.getKey(), e -> (String) e.getValue()));
Solution 3
Loop over the Set<String>
(which is Iterable
) that is returned by the stringPropertyNames()
method. When processing each property name, use getProperty
to get the property value. Then you have the information needed to put
your property values into your HashMap
.
Admin
Updated on July 19, 2022Comments
-
Admin almost 2 years
This nice article shows us how to print all the current system properties to STDOUT, but I need to convert everything that's in
System.getProperties()
to aHashMap<String,String>
.Hence if there is a system property called "baconator", with a value of "yes!", that I set with
System.setProperty("baconator, "yes!")
, then I want theHashMap
to have a key ofbaconator
and a respective value ofyes!
, etc. Same idea for all system properties.I tried this:
Properties systemProperties = System.getProperties(); for(String propertyName : systemProperties.keySet()) ;
But then get an error:
Type mismatch: cannot convert from element type Object to String
So then I tried:
Properties systemProperties = System.getProperties(); for(String propertyName : (String)systemProperties.keySet()) ;
And am getting this error:
Can only iterate over an array or an instance of java.lang.Iterable
Any ideas?