Search code examples
javalocale

Translate country name into other language


I searched for a solution, but I have not found any.

I have this kind of information:

String locale = "en_GB";
String country = "Japonia"; //It means Japan in polish

I need to translate the country name "Japonia" into language indicated in string locale, so "Japan". Is there any way to do it?


Solution

  • Assuming you know both the input language and the desired output language, an alternative approach - iterate the Locale(s) on the system using Locale.getAvailableLocales(), test if the country name matches from the desired in Locale - if so display it in the desired output Locale using getDisplayCountry(Locale)

    String country = "Japonia";
    Locale outLocale = Locale.forLanguageTag("en_GB");
    Locale inLocale = Locale.forLanguageTag("pl-PL");
    for (Locale l : Locale.getAvailableLocales()) {
        if (l.getDisplayCountry(inLocale).equals(country)) {
            System.out.println(l.getDisplayCountry(outLocale));
            break;
        }
    }
    

    Outputs

    Japan
    

    And if you modify the outLocale like

    Locale outLocale = Locale.forLanguageTag("es-SP");
    

    you get

    Japón