How to efficiently write hundred of “if then else”

  • A+
Category:Languages

I have this function

private static string countryToLanguage(String countryCode){    if (countryCode.equal("AD")) {return "ca"}   else if (countryCode.equal("AE")) {return "ar"}   else if (countryCode.equal("AG")) {return "en"}   ...  } 

Is their any more efficient way to do this? As it's a static function i can't use any kind of global variable (like hashmap)

 


As it's a static function i can't use any kind of global variable (like hashmap)

Sure you can.

private static final HashMap<String, String> LANGUAGES = new HashMap<>();  static {   LANGUAGES.put("AD", "ca");   // TODO: rest of mappings go here }  private static String countryToLanguage(String countryCode){   return LANGUAGES.get(countryCode); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: