I created an enum that includes 4 address formats. I know which country uses which format, and I’m trying to create a HashMap that will include countries as key, and formats as value. I want to get address format of a country with O(1) time complexity.
static final HashMap<String, Format> countries = new HashMap<>();
static {
for (Format format : Format.values()) {
for (String country : format.getCountries()) {
countries.put(country, format);
}
}
}
public static Optional<Format> fromCountry(String country) {
return Optional.ofNullable(countries.get(country));
}
And example Format enum is:
FORMAT1("[num] [road]", ["AD", "AE", "AG", "......", "ZA", "ZM", "ZW"])
My app is multi-threaded, but I won’t put any data to this map after the initialization, and I will only get a value from this map using fromCountry()
method above. In this case, can I use HashMap or do I need to use ConcurrentHashMap? Is there a better way than using these?
Hacı Efendi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.