Search code examples
javahashmapsystem-properties

How to convert all Java System Properties to HashMap<String,String>?


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?


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