Java Get All Locales using Apache Commons Lang

Tags: LocaleUtils Apache Commons Apache Commons Lang Locale

This Java tutorial shows you how to use the LocaleUtils class in Apache Commons Lang library to get the list of all installed locales.

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 all Locales in Java

The Apache Commons Lang library provides the method LocaleUtils.availableLocaleList() to return the unmodifiable list of installed locales. This method is a wrapper of JDK Locale.getAvailableLocales() method with the advantage that it does not create a new array each time we call the method. You can learn how to use this method in the following example code.

GetAvailableLocaleList.java

import org.apache.commons.lang3.LocaleUtils;

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

public class GetAvailableLocaleList {
    public static void main(String... args) {
        List<Locale> locales = LocaleUtils.availableLocaleList();

        for(Locale locale : locales) {
            System.out.println(locale.getDisplayName());
        }
    }
}
The output is:
Arabic (United Arab Emirates)
Arabic (Jordan)
Arabic (Syria)
Croatian (Croatia)
French (Belgium)
Spanish (Panama)
Maltese (Malta)
Spanish (Venezuela)
Bulgarian
Chinese (Taiwan)
Italian
Korean
Ukrainian
Latvian
Danish (Denmark)
Spanish (Puerto Rico)
Vietnamese (Vietnam)
English (United States)
...
English (United Kingdom)

There is a similar method LocaleUtils.availableLocaleSet() which returns an unmodifiable set of available locales as the following example code.

GetAvailableLocaleSet.java

import org.apache.commons.lang3.LocaleUtils;

import java.util.Locale;
import java.util.Set;

public class GetAvailableLocaleSet {
    public static void main(String... args) {
        Set<Locale> locales = LocaleUtils.availableLocaleSet();

        for(Locale locale : locales) {
            System.out.println(locale.getDisplayName());
        }
    }
}
The output is:
Arabic (United Arab Emirates)
Arabic (Jordan)
Arabic (Syria)
Croatian (Croatia)
French (Belgium)
Spanish (Panama)
Maltese (Malta)
Spanish (Venezuela)
Bulgarian
Chinese (Taiwan)
Italian
Korean
Ukrainian
Latvian
Danish (Denmark)
Spanish (Puerto Rico)
Vietnamese (Vietnam)
...
Indonesian (Indonesia)
English (United Kingdom)

Happy Coding 😊