Java 17 Recipes


-3. Matching and Filtering Locales


Download 3.2 Mb.
Pdf ko'rish
bet206/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   202   203   204   205   206   207   208   209   ...   245
Bog'liq
Java 17 Recipes

11-3. Matching and Filtering Locales
 Problem
You want to match against or filter a list of locales and return only those that meet the 
specified criteria.
 Solution
Make use of the new locale matching and filtering methods that have been introduced 
in the java.util.Locale class in Java 8. If you’re given a comma-separated list of locales 
in string format, you can apply a filter or “priority list” to that string to return only those 
locales within the string that meet the filter. In the following example, a list of language 
tags is filtered using the java.util.Locale filterTag method, returning the matching 
tags in string format.
public static void main(String[] args) {
filterTags();
localeMatching();
}
public static void filterTags(){
List list1 = Locale.LanguageRange.parse 
("ja-JP, en-US");
list1.stream().forEach((range) -> {
System.out.println("Range:" + range.getRange());
});
ArrayList localeList = new ArrayList();
localeList.add("en-US");
localeList.add("en-JP");
List tags1 = Locale.filterTags(list1, localeList);
System.out.println("The following is the filtered list of 
locales:");
tags1.stream().forEach((tag) -> {
System.out.println(tag);
});
}
Chapter 11 UniCode, internationalization, and CUrrenCy Codes 


407
These are the results.
Range:ja-jp
Range:en-us
The following is the filtered list of Locales:
en-us
The filter() method of the Locale classes allows you to return a list of matching 
Locale instances. In the following example, a list of locale language tags filters Locale 
classes out of a list of locales.
public static void localeMatching(){
String localeTags = Locale.ENGLISH.toLanguageTag() + "," +
Locale.CANADA.toLanguageTag();
List list1 = Locale.LanguageRange.
parse(localeTags);
list1.stream().forEach((range) -> {
System.out.println("Range:" + range.getRange());
});
ArrayList localeList = new ArrayList();
localeList.add(new Locale("en"));
localeList.add(new Locale("en-JP"));
List tags1 = Locale.filter(list1, localeList);
System.out.println("The following is the matching list of Locales:");
tags1.stream().forEach((tag) -> {
System.out.println(tag);
});
}
Here are the results.
Range:en
Range:en-ca
The following is the matching list of locales:
en
Chapter 11 UniCode, internationalization, and CUrrenCy Codes 


408

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   202   203   204   205   206   207   208   209   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling