巧用Java List.removeAll()方法判定列表中元素是否都是某集合中的元素

假設我們有這樣一個需求,需要判定配置的 OAuth2 授權類型,是否都在有效範圍內。OAuth2 的授權類型只能是這五種:"refresh_token",
"password", "client_credentials", "authorization_code", "implicit",因爲用戶可以配置的值可能不在這五種授權類型中,所以需要判定。

removeAll(Collection<?>c)方法用於從列表中移除指定 collection 中包含的所有元素,我們可以利用這個方法來進行判定。

首先定義支持的授權類型:

    /**
     * 支持的授權類型
     */
    public static final List<String> GRANT_TYPES = Arrays.asList(new String[]{"refresh_token",
            "password", "client_credentials", "authorization_code", "implicit"});

接着把用戶所傳入的授權類型放入新的列表 temp,然後使用removeAll() 移除掉支持的授權類型,如果列表 temp 不爲空,則所以存在超出範圍的授權類型,因此直接拋出異常:

            List<String> temp = new ArrayList<>(grantTypes);
            temp.removeAll(GRANT_TYPES);
            if (!temp.isEmpty()) {
                throw new IllegalArgumentException("OAuths2 賬戶名 [" + name + "] " +
                        "下的授權類型只能是這些類型:" + GRANT_TYPES);
            }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章