Wednesday, August 17, 2016

How to work with locales

In order to understand how to make use of locales in Java, let's try two useful examples. First, assume that you want to extract available locales speaking French which has the code "fr":

import java.util.Arrays;
import java.util.Locale;

class AvailableLocalesFrench {
public static void main(String[] args) {
Arrays.stream(Locale.getAvailableLocales()).filter(locale -> locale.getLanguage().equals("fr"))
.forEach(locale -> System.out.printf("Locale code: %s and it stands for %s %n", locale,
locale.getDisplayName()));
}
}

By running this you would get:

Locale code: fr_BE and it stands for French (Belgium) 
Locale code: fr_CH and it stands for French (Switzerland) 
Locale code: fr and it stands for French 
Locale code: fr_LU and it stands for French (Luxembourg) 
Locale code: fr_FR and it stands for French (France) 
Locale code: fr_CA and it stands for French (Canada)

The Second example, let's set the default locale within the system to France and get some details about it:

import java.util.Locale;

public class LocaleDetails {
public static void main(String args[]) {
Locale.setDefault(Locale.FRANCE);
Locale defaultLocale = Locale.getDefault();
System.out.printf("The default locale is %s %n", defaultLocale);
System.out.printf("The default language code is %s and the name is %s %n", defaultLocale.getLanguage(),
defaultLocale.getDisplayLanguage());
System.out.printf("The default country code is %s and the name is %s %n", defaultLocale.getCountry(),
defaultLocale.getDisplayCountry());
System.out.printf("The default variant code is %s and the name is %s %n", defaultLocale.getVariant(),
defaultLocale.getDisplayVariant());
}
}

Outputs:

The default locale is fr_FR 
The default language code is fr and the name is français 
The default country code is FR and the name is France 
The default variant code is  and the name is

No comments:

Post a Comment