Im relativly new to Java and i ran into some problems. The goal is to compare the parameters, e.g. -DmyCustomArg="my_value"
, i specify in the jvm with the map and overwrite the matching key with new value.
So i have two hashmaps, one is the System.getProperties()
and the other is a map with parameters. Now I want to compare both and replace matching values.
I have already tried
Map properties = System.getProperties();
Map<String, String> parameter = new HashMap<>();
parameter.put("1", "value one");
parameter.put("2", "value two");
parameter.put("myCustomArg", "value three");
for (int i = 0; i < parameter.keySet().toArray().length; i ) {
if (properties.containsKey(parameter.keySet().toArray()[i])) {
parameter.replace(properties.get( ??? ))
}
}
But now I can't get any further. How do I get to the value where it matched so I can replace it? Do I have to create a third map where the results are stored or is there an easier way?
CodePudding user response:
welcome,
You can use this forEach loop:
Properties properties = System.getProperties();
Map<String, String> map = new HashMap<>();
map.put("1", "value one");
map.put("2", "value two");
map.put("myCustomArg", "value three");
map.forEach((key, value)->{
if(properties.containsKey(key)){
System.setProperty(key, value);
}
});
or if you'd like to loop the entry set without lambda, you can replace the map.forEach() with this:
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(properties.containsKey(key)){
System.setProperty(key, value);
}
}
or if you'd like to loop the keys only:
for (String key : map.keySet()) {
if(properties.containsKey(key)){
System.setProperty(key, map.get(key));
}
}
CodePudding user response:
If you need to override the properties is enough to use the same key value in the map. Map will replace previous value.
E.g:
Map systemProperties = System.getProperties();
System.out.println("java.runtime.version before: " systemProperties.get("java.runtime.version"));
systemProperties.put("java.runtime.version", "17.0.0");
// Print the new value
System.out.println("java.runtime.version after: " systemProperties.get("java.runtime.version"));