检查字符串是否是Java中ISO语言的ISO国家/地区的更简洁方法 [英] Cleaner way to check if a string is ISO country of ISO language in Java

查看:177
本文介绍了检查字符串是否是Java中ISO语言的ISO国家/地区的更简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有两个字符String,应表示 ISO 639 国家或语言名称.

Suppose to have a two-characters String, which should represent the ISO 639 country or language name.

您知道, Locale 类具有两个功能 getISOLanguages 分别返回包含所有ISO语言和ISO国家/地区的String数组.

You know, Locale class has two functions getISOLanguages and getISOCountries that return an array of String with all the ISO languages and ISO countries, respectively.

要检查特定的String对象是否是有效的ISO语言或ISO国家/地区,我应该在数组内部查找匹配的String.好的,我可以使用二进制搜索(例如

To check if a specific String object is a valid ISO language or ISO country I should look inside that arrays for a matching String. Ok, I can do that by using a binary search (e.g. Arrays.binarySearch or the ApacheCommons ArrayUtils.contains).

问题是:存在任何实用程序(例如,来自 Guava Apache Commons 库),它提供了一种更简洁的方法,例如返回boolean以将String验证为有效的ISO 639语言或ISO 639国家(地区)的功能?

The question is: exists any utility (e.g. from Guava or Apache Commons libraries) that provides a cleaner way, e.g. a function that returns a boolean to validate a String as a valid ISO 639 language or ISO 639 Country?

例如:

public static boolean isValidISOLanguage(String s)
public static boolean isValidISOCountry(String s)

推荐答案

我不会费心使用二进制搜索或任何第三方库-HashSet对此很合适:

I wouldn't bother using either a binary search or any third party libraries - HashSet is fine for this:

public final class IsoUtil {
    private static final Set<String> ISO_LANGUAGES = new HashSet<String>
        (Arrays.asList(Locale.getISOLanguages()));
    private static final Set<String> ISO_COUNTRIES = new HashSet<String>
        (Arrays.asList(Locale.getISOCountries()));

    private IsoUtil() {}

    public static boolean isValidISOLanguage(String s) {
        return ISO_LANGUAGES.contains(s);
    }

    public static boolean isValidISOCountry(String s) {
        return ISO_COUNTRIES.contains(s);
    }
}

可以先检查字符串长度,但是我不确定是否会打扰-至少不会,除非您想保护自己免受性能攻击,否则会收到大量字符串,会花很长时间进行哈希处理.

You could check for the string length first, but I'm not sure I'd bother - at least not unless you want to protect yourself against performance attacks where you're given enormous strings which would take a long time to hash.

如果您想使用第三方库,请 ICU4J 是最有可能的竞争者-但列表可能比Locale支持的列表更新得多,因此,您可能想在所有地方使用ICU4J.

If you do want to use a 3rd party library, ICU4J is the most likely contender - but that may well have a more up-to-date list than the ones supported by Locale, so you would want to move to use ICU4J everywhere, probably.

这篇关于检查字符串是否是Java中ISO语言的ISO国家/地区的更简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆