如何检查Currency.getAvailableCurrencies()是否包含我的String值?

时间:2019-07-19 13:31:50

标签: java currency

我需要检查Currency.getAvailableCurrencies()是否包含 我的货币是字符串

我已经尝试过了

if(Currency.getAvailableCurrencies().contains("my currency")){
  // do something
}

但是返回false,但是包含"my currency"吗?

2 个答案:

答案 0 :(得分:1)

Currency.getAvailableCurrencies()返回Set<Currency> doc,因此您尝试检查String对象的Set中的Currency,该对象返回{{1} }总是。您需要使用输入字符串创建false对象,使用Currency.getInstance获取Currency实例

Currency

答案 1 :(得分:1)

正如@JBNizet在评论中所说,该方法返回Set中的Currency

您可以使用以下代码段检查您的货币是否可用:

Currency.getAvailableCurrencies().stream()
              .map(Currency::getCurrencyCode)
              .anyMatch(Predicate.isEqual("my currency"));

Currency.getInstance可能返回的所有内容始终都在该Set中,因此通过Currency.getAvailableCurrencies().contains(Currency.getInstance("my currency"))进行的测试基本上毫无意义。

运行此代码段时:

    @Test
    public void currency() {
        final Set<Currency> currencies = Currency.getAvailableCurrencies();
        System.out.println(currencies.size());

        for (char c0 = '0'; c0 <= 'Z'; c0 = inc(c0)) {
            for (char c1 = '0'; c1 <= 'Z'; c1 = inc(c1)) {
                for (char c2 = '0'; c2 <= 'Z'; c2 = inc(c2)) {
                    final String currencyCode = new String(new char[]{c0, c1, c2});
                    try {
                        final Currency currency = Currency.getInstance(currencyCode);

                        if (!currencies.contains(currency)) {
                            System.out.println("found currency that is not available: " + currency);
                        }
                    } catch (Exception e) { }
                }
            }
        }

        System.out.println(Currency.getAvailableCurrencies().size());
    }

    private char inc(char c) {
        if (c == '9') {
            return 'A';
        } else {
            return ++c;
        }
    }

您将永远找不到一个不可用的