封裝項目中高頻的「字符串 ⇄ 集合」轉換邏輯,提供統一、可複用、健壯的工具方法。
public static SetparseParameterList(String values) { Set result = new TreeSet<>(); // 自動去重+排序 if (values != null && values.trim().length() > 0) { // \\s+ 匹配任意空白字符(空格、制表、換行) String[] tokens = values.split("[\\s+]"); result.addAll(Arrays.asList(tokens)); } return result; }
應用場景:解析 HTTP 參數 `scope=read write execute`
public static String formatParameterList(Collectionvalue) { return value == null ? null : StringUtils.collectionToDelimitedString(value, ","); }
依賴 Spring `StringUtils`,輸出 `a,b,c` 格式
public static MapextractMap(String query) { Map map = new HashMap<>(); // query 格式: name=god&password=111&method=up Properties props = StringUtils.splitArrayElementsIntoProperties( StringUtils.delimitedListToStringArray(query, "&"), "="); if (props != null) { props.forEach((k, v) -> map.put(k.toString(), v.toString())); } return map; }
public static boolean containsAll(Settarget, Set members) { target = new HashSet<>(target); // 複製避免修改原集合 target.retainAll(members); // 取交集 return target.size() == members.size(); // members 全在 target 中 }
// 1. 解析權限範圍 Setscopes = MyStringUtils.parseParameterList("read write execute"); System.out.println(scopes); // [execute, read, write] (TreeSet 排序) // 2. 組裝回傳字符串 String scopeStr = MyStringUtils.formatParameterList(scopes); // "execute,read,write" // 3. 解析回調參數 Map params = MyStringUtils.extractMap("user=admin&action=login&token=xyz"); // {user=admin, action=login, token=xyz} // 4. 權限校驗 boolean hasAll = MyStringUtils.containsAll(userScopes, requiredScopes);