Reputation: 675
I have a an ISO 4217 numeric currency code: 840
I want to get the currency name: USD
I am trying to do this:
Currency curr1 = Currency.getInstance("840");
But I keep getting
java.lang.IllegalArgumentException
how to fix? any ideas?
Upvotes: 11
Views: 14449
Reputation: 193
I have reviewed other comments as well, but the most efficient working version is as follows:
public final class CurrencyFinder {
private CurrencyFinder() {
}
private static final Set<Currency> AVAILABLE_CURRENCIES = Currency.getAvailableCurrencies();
public static Optional<Currency> find(String currencyCode) {
return AVAILABLE_CURRENCIES.stream()
.filter(currency -> Objects.equals(currency.getCurrencyCode(), currencyCode))
.findFirst();
}
public static Optional<Currency> find(Integer numericCode) {
return AVAILABLE_CURRENCIES.stream()
.filter(currency -> currency.getNumericCode() == numericCode)
.findFirst();
}
}
While making these transformations, I noticed that some
numericCode
values are the same, which I consider to be an important point to be aware of. Especially if a project is to be undertaken, I recommend working with thecurrencyCode
value instead of thenumericCode
value.
Upvotes: 1
Reputation: 192
A better way to do it:
public class CurrencyHelper {
private static Map<Integer, Currency> currencies = new HashMap<>();
static {
Set<Currency> set = Currency.getAvailableCurrencies();
for (Currency currency : set) {
currencies.put(currency.getNumericCode(), currency);
}
}
public static Currency getInstance(Integer code) {
return currencies.get(code);
}
}
With a little work the cache can be made more efficient. Please take a look at the source code the Currency class for more information.
Upvotes: 6
Reputation: 2217
With Java 8:
Optional<Currency> currency = Currency.getAvailableCurrencies().stream().filter(c -> c.getNumericCode() == 840).findAny();
Upvotes: 9
Reputation: 279
You have to provide code like "USD" and then it will return Currency object. If you are using JDK 7 then you can use following code. JDk 7 has a method getAvailableCurrencies()
public static Currency getCurrencyByCode(int code) {
for(Currency currency : Currency.getAvailableCurrencies()) {
if(currency.getNumericCode() == code) {
return currency;
}
}
throw new IllegalArgumentException("Unkown currency code: " + code);
}
Upvotes: 0
Reputation: 31269
java.util.Currency.getInstance
supports only ISO 4217 currency codes, not currency numbers. However, you can retrieve all currencies using the getAvailableCurrencies
method, and then search for the one with code 840 by comparing the result of the getNumericCode
method.
Like this:
public static Currency getCurrencyInstance(int numericCode) {
Set<Currency> currencies = Currency.getAvailableCurrencies();
for (Currency currency : currencies) {
if (currency.getNumericCode() == numericCode) {
return currency;
}
}
throw new IllegalArgumentException("Currency with numeric code " + numericCode + " not found");
}
Upvotes: 13