在項目中,我們經常需要把接收到的字符串轉換成對應的集合類保存,或者把集合類轉換成字符串以方便傳輸,這個工具類中封裝了幾個常用的方法,對於這種轉換需求十分方便。
import java.util.Arrays;import java.util.Collection;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Properties;import java.util.Set;import java.util.TreeSet;public class MyStringUtils { /** * 將字符串轉換成set集合類* 分隔符是任意空白字符*/ public static Set<String> parseParameterList(String values) { Set<String> result = new TreeSet<String>(); if (values != null && values.trim().length() > 0) { // the spec says the scope is separated by spaces String[] tokens = values.split("[//s+]");//匹配任意空白字符result.addAll(Arrays.asList(tokens)); } return result; } /** * 把集合轉化成指定形式的字符串*/ public static String formatParameterList(Collection<String> value) { return value == null ? null : StringUtils.collectionToDelimitedString(value, ",");//指定分隔符} /** * 從query的字符串中抽取需要的鍵值對存入map中* query的形式name=god&password=111&method=up */ public static Map<String, String> extractMap(String query) { Map<String, String> map = new HashMap<String, String>(); Properties properties = StringUtils.splitArrayElementsIntoProperties( StringUtils.delimitedListToStringArray(query, "&"), "="); if (properties != null) { for (Object key : properties.keySet()) { map.put(key.toString(), properties.get(key).toString()); } } return map; } /** * 比較兩個集合是否相等*/ public static boolean containsAll(Set<String> target, Set<String> members) { target = new HashSet<String>(target); target.retainAll(members);//取兩個集合的交集return target.size() == members.size(); }}以上這篇淺談常用字符串與集合類轉換的工具類就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。