Is there an easy way in Java to get the ISO2 code from a given country name, for example "CH" when given "Switzerland"?
The only solution I can think of at the moment is to save all the country codes and names in an array and iterate over it. Any other (easier) solutions?
Use a
Map
, not an array, then you don't have to iterate over it, you just look it up.O(1) vs O(n)
note that you will walk the stream every time you call the method, it is more efficient to use a map or save the result in a lookup table
As others have mentioned Map is the easiest way, here's what I wrote/used where I had the same problem.
concat flag to url(https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/0.8.2/flags/1x1/)
Use a java.util.Map instead of an array.
CountryCode enum contained in com.neovisionaries:nv-i18n:1.11 (or later) has
findByName
methods to list up country codes whose names match a given pattern.To get "CH" from "Switzerland":
GitHub
https://github.com/TakahikoKawasaki/nv-i18n
JavaDoc
http://takahikokawasaki.github.io/nv-i18n/
Maven