Java Get Languages by Country Code using Apache Commons Lang

Tags: LocaleUtils Apache Commons Apache Commons Lang Locale

In this Java tutorial we learn how to get the list of languages supported for a specific country using the LocaleUtils class of Apache Commons Lang library.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to get Locale Languages by Country Code in Java

The Apache Commons Lang library provides the method LocaleUtils.languagesByCountry() to obtain the list of languages supported for a given country code. For example in the below Java program we get languages supported in the United States (US) and Australia (AU).

GetLanguagesByCountry.java

import org.apache.commons.lang3.LocaleUtils;

import java.util.List;
import java.util.Locale;

public class GetLanguagesByCountry {
    public static void main(String... args) {
        List<Locale> languagesByUS = LocaleUtils.languagesByCountry("US");

        System.out.println("Languages at United States:");
        for(Locale locale : languagesByUS) {
            System.out.println(locale.getDisplayLanguage());
        }

        List<Locale> languagesByAU = LocaleUtils.languagesByCountry("AU");

        System.out.println("Languages at Australia:");
        for(Locale locale : languagesByAU) {
            System.out.println(locale.getDisplayLanguage());
        }
    }
}
The output is:
Languages at United States:
English
Spanish
Languages at Australia:
English

Happy Coding 😊