'Get a hard-coded value using combination of multiple keys
I've to store hard-coded value in my environment files like this:
- folder.canada.6m.ind=150992762918
- folder.canada.9m.group=150992760518
- folder.usa.1m.ind=150992762995
There are 3 parameters (String country, String months, String category) which I receive from the end user and I've to pick the corresponding value from env files.
I can do it using brute force like,
if(country.equals(canada) && months.equals(6m) && category.equals(ind)) {
return folder.canada.6m.ind;
}
There are other ways to do it using if-else as well but I have 100's of these values so I don't think the best way to solve this problem is using if-else. What would be the best data structure or method to solve this problem?
I'm using spring-boot in Java.
Solution 1:[1]
Spring boot can put your properties into a map. Let's have a look at the following class:
@Configuration
@ConfigurationProperties(prefix = "")
public class FolderConfig {
private Map<String, String> folder = new HashMap<>();
public void setFolder(Map<String, String> folder) {
this.folder = folder;
}
public String getValue(String country, String month, String category) {
String key = String.format("%s.%s.%s", country, month, category);
return folder.get(key);
}
}
The naming of the map is important, because it is used as prefix of your properties keys! This means, the map folder has the following values:
canada.6m.ind=150992762918
canada.9m.group=150992760518
usa.1m.ind=150992762995
You see your keys don't start with folder!
Maybe you should think about throwing an additional exception, if the key doesn't exists.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
