How to get the language code based on country code in java

How to get the language code based on country code in java
Hi
I had a situation where I need to find the language based on country code.
For country name "switzerland" I had country code as "CH" .
But there can be 3 languges like German,french and ukenglish in Switzerland . I need to find the language code based on country code.
Scenario : My country code is "CH" . I need to get the language code based on this country code.

Thanks in advance

Upvotes: 2

Views: 8446

Answers (2)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

This program prints the language codes for all available locales for Switzerland. It can easily be modified to e.g. return a List<String> of language codes. Picking the one you want is left as an exercise for the reader - the Swiss have not chosen to pick a single preferred language for their country.

import java.util.Locale;

public class Test {
  public static void main(String[] args) {
    Locale[] all = Locale.getAvailableLocales();
    for (Locale locale : all) {
      String country = locale.getCountry();
      if(country.equalsIgnoreCase("CH")){
        System.out.println(locale.getLanguage());
      }
    }
  }
}

Output:

fr
de
it

Upvotes: 9

Razib
Razib

Reputation: 11163

You can use following constructor of Locale -

   Locale(String language, String country)

For USA (code: US) the language is English (code "en"). So you can do this -

Locale locale = new Locale("en", "US");

Upvotes: 0

Related Questions