29 março 2014

Get all countries using Java SE 8 Locale

I saw this blog post "Get all the country using Java Locale List" and then I thought about posting something similar, but using Lambda and the Stream API of Java SE 8. Here's my "fork", including a call to sort the locales based on "display country" property.

package foo;
import java.util.Arrays;
import java.util.Locale;
/**
* @author bruno borges
*/
public class Foo {
public static void main(String[] args) {
final String formatOutput = "Country : %s \t\t\t\t:\t Country Code : %s";
List<String> list =
Arrays.asList(Locale.getISOCountries())
.stream()
.map(c -> new Locale("", c))
.sorted((c0, c1) -> c0.getDisplayCountry().compareTo(c1.getDisplayCountry()))
.map(l -> String.format(formatOutput, l.getDisplayCountry(), l.getCountry()))
.collect(Collectors.toList());
list.forEach(System.out::println);
}
}
view raw Foo.java hosted with ❤ by GitHub


And if you want to collect all that to a list instead of printing to standard output, replace the last forEach call with collect(Collectors.toList()); and assign a variable.

Nenhum comentário:

Contato

Email:bruno.borges(at)gmail.com

LinkedIn: www.linkedin.com/in/brunocborges
Twitter: www.twitter.com/brunoborges
Comprei e Não Vou
Rio de Janeiro, RJ Brasil
Oracle
São Paulo, SP Brasil