Java Convert String to Locale using Apache Commons Lang

Tags: LocaleUtils Apache Commons Apache Commons Lang Locale Convert String

In this Java tutorial we show you how to convert a String value into a Locale object 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 convert a String to Locale in Java

The Apache Commons Lang provides the method LocaleUtils.toLocale() to convert a String object into a Locale object as the below code example.

ConvertStringToLocale.java

import org.apache.commons.lang3.LocaleUtils;

import java.util.Locale;

public class ConvertStringToLocale {
    public static void main(String... args) {
        Locale locale1 = LocaleUtils.toLocale("en");
        Locale locale2 = LocaleUtils.toLocale("en_AU");

        System.out.println(locale1.getDisplayName());
        System.out.println(locale2.getDisplayName());
    }
}
The output is:
English
English (Australia)

Happy Coding 😊