How do I get all available currency codes?

The example presented in this code snippet show you how to get the available currency codes. We will need the locale information and use the Currency class for this example.

package org.kodejava.util;

import java.util.Currency;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

public class CurrencySymbolDemo {
    public static void main(String[] args) {
        CurrencySymbolDemo cs = new CurrencySymbolDemo();

        Map<String, String> currencies = cs.getAvailableCurrencies();
        for (String country : currencies.keySet()) {
            String currencyCode = currencies.get(country);
            System.out.println(country + " => " + currencyCode);
        }
    }

    /**
     * Get the currencies code from the available locales information.
     *
     * @return a map of currencies code.
     */
    private Map<String, String> getAvailableCurrencies() {
        Locale[] locales = Locale.getAvailableLocales();

        // We use TreeMap so that the order of the data in the map sorted
        // based on the country name.
        Map<String, String> currencies = new TreeMap<>();
        for (Locale locale : locales) {
            try {
                currencies.put(locale.getDisplayCountry(),
                        Currency.getInstance(locale).getCurrencyCode());
            } catch (Exception e) {
                // when the locale is not supported
            }
        }
        return currencies;
    }
}

You will have something like this printed on the screen:

...
Honduras => HNL
Hong Kong SAR China => HKD
Hungary => HUF
Iceland => ISK
India => INR
Indonesia => IDR
Iran => IRR
Iraq => IQD
Ireland => EUR
Isle of Man => GBP
...
Wayan

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.