how to make key of map to variable name - java

In java,i have a Map that contains certain values. I want to create a String variable that having the name of the key of the map. How it is possible in java?
Map<String,String> values=new HashMap<String, String>();
values.put("dataSource", "bloomberg");
values.put("dataProvider", "bloomberg");
values.put("observationTime", "close");
this is the map. And i want to make the variables with values :
String dataSource="bloomberg";
String dataProvider="bloomberg";
String observationTime="close";
How it is possible in java?

Java doesn't support dynamic variable names. All the variables have to be present at compile time (this means that only the containers would be made at compile time) and at runtime, values are simply assigned and changed according to the logic of the program.
A few languages support creating variables with dynamic names, but it is not possible in Java

Try this
String dataSourceKey = "dataSource";
String dataSourceValue = "bloomberg";
values.put(dataSourceKey, dataSourceValue);
Now, when reading the values from the map
String dataSource = values.get(dataSourceKey);
Hope this helps

Related

Putting values into an inner Map

I have a ConcurrentHashMap that looks like this:
private Map<String,Map<String,Set<PublicKey>>> instancePairs = new ConcurrentHashMap<>();
And a method that is supposed to fill this hashmap up.
But i can't figure out how to put the values in the map
Currently i have:
instancePairs.putIfAbsent(inMemoryInstance.getUsername(), inMemoryInstance.getId() , publicKeySet);
Intellij Idea is giving me this error:
As mentioned by "DDovzhenko", you'd need to do something along the following lines.
//Get the map containing the ID as keys, if it doesn't exist, then create one.
Map mapValuesForName = instancePairs.getOrDefault(inMemoryInstance.getUsername(), new ConcurrentHashMap<String,Set<PublicKey>>());
//Put the publicKeySet based on the Id.
mapValuesForName.putIfAbsent(inMemoryInstance.getId(), publicKeySet);
//Store the potentially changed/new value back in original map.
instancePairs.put(mapValuesForName);

Replace shell environment variables in a string with actual values

I am reading a property file in Java.
Properties myProp = new Properties();
InputStream in = new FileInputStream(pathOfPropertyFile);
myProp.load(in);
in.close();
The values in the property file have references to Linux shell variables.
For example, an entry in the property file might look like:
DATA_PATH=/data/${PROJECT}/${YEAR}${MONTH}${DAY}
I have to execute a shell script from java and so I have ProcessBuilder instance and also the environment variables (envMap as given below):
List<String> command = new ArrayList<String>();
command.add(actualCommand);
command.add(param1);
command.add(param2);
ProcessBuilder processBuilder = new ProcessBuilder(command);
Map<String, String> envMap = processBuilder.environment();
The envMap has the environment variables I require along with over one hundred (> 100) other environment variables which I do not require.
I want to replace the ${USER},${PROJECT},etc., from the property-value string "/home/${USER}/${PROJECT}/data" with actual values from the shell.
I would consider iterating the Map as the last option(as the Map has between 100 and 200 elements to iterate) as it is not an efficient approach.
Please advise some approach that will fetch the environment variable enclosed by braces from the string, so that I can directly use the get() of the Map and replace. Or, any better approaches are most welcome.
Note: The reference offered ( Replace String values with value in Hash Map that made my question to look duplicate) is not the best fit in my case.
If you are open to using an external library, StrSubstitutor from apache-commons will do exactly what you want:
public static void main(String[] args) {
String input = "DATA_PATH=/data/${PROJECT}/${YEAR}${MONTH}${DAY}";
Map<String, String> env = new HashMap<>();
env.put("PROJECT", "myProject");
env.put("YEAR", "2017");
env.put("MONTH", "7");
env.put("DAY", "5");
env.put("OTHER_VALUE", "someOtherValue");
System.out.println(StrSubstitutor.replace(input, env));
}
Output:
DATA_PATH=/data/myProject/201775
It also has a method to directly replace system properties without the need for an explicit map.
(for a non-external-library approach see vefthym's answer)
I am not sure if it works, but I hope someone can edit to make it work, or at least you get the logic and make it work on your own:
command = command.replaceAll("\\$\\{(.*?)\\}", envMap.get("$1"));
Here, I am assuming that command is a String (not a List) and that all environment variables exist in your Map (otherwise you should check for null and handle this case as you wish).
A bit of an explanation:
this regex is looking for the pattern "${something}" and replaces it with envMap.get("something"). In this example, we use parentheses to mark "something" as a group, which can then be retracted as "$1" (since we have only one group, i.e., only one set of parentheses).
The question mark '?' is the non-greedy operator here meaning to stop at the smallest possible regex match (otherwise it would find a singe match for the first "${" until the last "}".

Howto check if a TreeMap contains a specific object?

In an application I have this TreeMap object:
treePath = new TreeMap<String, DLFolder>();
The first String parameter should be the key and the DLFolder is the value.
Ok the DLFolder object have this method dlFolder.getPath() that return a String
So I want to know if the treePath object contains a DLFolder object having a specific path value
Can I do this thing?
Tnx
for (DLFolder dlf : treePath.values()) {
if ("A SPECIFIC PATH".equals(dlf.getPath()) {
// do someting with the dlf
}
In Java 8 this is rather straightforward.
treePath.values().anyMatch(dlf -> dlf.getPath().equals(specificValue))
You can loop through the values of the TreeMap:
for (DLFoder folder : treePath.values())
if (folder.getPath().equals(somePathValue))
// path found!
If the map's key is also the value stored in dlFolder.getPath(), then yes, you can just call treePath.contains("Value");.
Other options include:
Iterating over treePath's values either using an iterator, an enhanced for loop, or the Java 8 streams.
Creating another map to map the same DLFolder objects, but by path.

Displaying struts validations message

I want to display errors detected in an action class, I use:
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("some_string_in_properties_file"));`
and it works fine. However, I have written some generic error messages, and I would like to reuse them, so I am trying to do this:
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("string1_in_properties_file", "string2_in_properties_file"));
where string1 = <li>{0} is required.</li>.
Then it is displaying string2 is required. It is not replacing string2 with its value.
I even tried
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("string1_in_properties_file",
new ActionMessage("string2_in_properties_file")));
then it is displaying string2[] is required. It is not replacing string2.
I know it can be done by hard-coding the value, but is there any other way?
Since you want to to fetch two key's value from Property file, and put it in global error key,
I would say, retrieve each value separately using
String sValue1 = getResources(request).getMessage(locale, "key1");
String sValue2 = getResources(request).getMessage(locale, "key2");
and then put it in your global error
errors.add(ActionErrors.GLOBAL_MESSAGE,sValue1+"<br/>"+sValue2);
Hope it help....
It's hard to tell you exactly what to do, since O don't know the code behind errors and ActionMessage. But you can, however, use String.format. Your code would look something like this
public class ActionErrors {
public static final String INVALID_INPUT "'%s' is not valid input.";
...
}
and
String input = "Cats";
String message = String.format(ActionErrors.INVALID_INPUT, input);
System.out.println(message);
The above will print
'Cats' is not valid input.
In Struts ActionMessage, you can specify value for your parameters {0}, {1}, {2}, {3} specified in your properties file, as follows:
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("some_string_in_properties_file", "value1"));
Alternately:
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage("some_string_in_properties_file", "value1", "value2", "value3"));
value1..value3 can be of any type (as Struts expects an Object).
so your property:
string1 = <li>{0} is required.</li>
Will be replaced to:
<li>value1 is required.</li>
(If you specify your key as string1).
Let's say you have a properties file that defines some keys for messages, like so:
string1: <li>{0} is required.</li>
string2: Username
The ActionMessage class has a number of constructors that take a varying number of arguments. The first is a string representing the key that refers to a message - in your case, the key is string1 which corresponds to the message <li>{0} is required.</li>; with the {0} being a placeholder for some dynamic content.
The remaining possible arguments are Objects that represent the actual values you want to replace those placeholders. If you do new ActionMessage("string1", "string2") you're passing in the literal value string2, and you'll end up with output of <li>string2 is required.</li>.
What you need to do is replace "string2" with a method call that will get the value that corresponds to the key string2. This is where my knowledge of the problem runs out, though, so you'll need to do some research on this part for yourself.

Reflecting an array in Java

I am new in Java and have a task to write some application. Faced one problem which can not pass :(
The issue is to update an array element through reflection (app selecting public array to update dinamicaly depending on string app reading from file):
First, i have reflected boolean variables as follows:
activity = activityName(activities[i].substring(0,activities[i].lastIndexOf('.', activities[i].length() - 4)));
Field field = refClass.getField(activity);
Object obj = field;
field.setBoolean(obj, true);
And that worked for me well. But now i need to use arrays instead of regular variables, and tried to make as follows:
activity = activityName(activities[i].substring(0, activities[i].lastIndexOf('.', activities[i].length() - 4)));
Field field = refClass.getField(activity);
Object field_act = field;
field_act.setBoolean(field_act, LMKStorage.currentLmkSlot, true);
And getting exception "Argument not an array". :(
In field_act.setBoolean(field_act, LMKStorage.currentLmkSlot, true);, field_act is boolean[] i am getting with .getField(activity), LMKStorage.currentLmkSlot is int to determine which position of an array to set and "true" is value to set. The field_act i have to get 100% is an array, because i have not non-array static variables in refClass.
so far i have got studing books i have.But still nothing. Tried to google any examples to update array elements... nothing usefull for me.
Please advice.
For arrays, use java.lang.reflect.Array instead of java.lang.reflect.Field.
Object field_act = field.get(obj);
Array.setBoolean(field_act, LMKStorage.currentLmkSlot, true);

Categories

Resources