Question

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 a HashMap<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 the HashMap to have a key of baconator and a respective value of yes!, 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?

Était-ce utile?

La solution

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());
}

Autres conseils

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()));

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.

This does work

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);
}

Either you can use the entrySet() method from Properties to get an Entry type from Properties which is Iterable or you could use the stringPropertyNames() method from the Properties class to get a Set of keys in this property list. The use the getProperty method to get the property value.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top