How do I pass an array or list of values to Java via system properties - and how do I access it?

arrays, environment-variables, java, list

Solution

From Oracle Javase tutorial On the Java platform, an application uses System.getenv to retrieve environment variable values. Without an argument, getenv returns a read-only instance of java.util.Map, where the map keys are the environment variable names, and the map values are the environment variable values.

So if you have an environment variable `MY_LIST=val1,val2,val3`, you can use it as simple as

String strlist = System.getenv().get("MY_LIST");
List<String> list = Arrays.asList(strlist.split(","));

Edit: fixed call of getenv (forgot parentheses - thanks to Christian)

I must precise that my anwer concerns environment variable which is the title of the post. But `java -D MY_LIST=a,b,c ...` sets system properties and it in not the same. To access system properties set by `-D` option, I should write instead :

String strlist = System.getProperty("MY_LIST");
List<String> list = Arrays.asList(strlist.split(","));

Problem

Is there a way to pass a list of values into Java, using only one system property? I'm thinking of something along the lines `-DMY_LIST=val1,val2,val3` or `-DMY_LIST={val1, val2}` Any ideas? How would I access that in Java? Update: I initially asked for environment variables, but actually meant system properties. Similar principle, but quite different... I changed title and text accordingly now. Thanks, @serge-ballesta

Original source