常用字符串与集合类转换的工具类

在项目中,我们经常需要把接收到的字符串转换成对应的集合类保存,或者把集合类转换成字符串以方便传输,这个工具类中封装了几个常用的方法,对于这种转换需求十分方便。

 1 import java.util.Arrays;
 2 import java.util.Collection;
 3 import java.util.HashMap;
 4 import java.util.HashSet;
 5 import java.util.Map;
 6 import java.util.Properties;
 7 import java.util.Set;
 8 import java.util.TreeSet;
 9 
10 public class MyStringUtils {
11 
12     /**
13      * 将字符串转换成set集合类
14      * 分隔符是任意空白字符
15      */
16     public static Set<String> parseParameterList(String values) {
17         Set<String> result = new TreeSet<String>();
18         if (values != null && values.trim().length() > 0) {
19             // the spec says the scope is separated by spaces
20             String[] tokens = values.split("[\\s+]");//匹配任意空白字符
21             result.addAll(Arrays.asList(tokens));
22         }
23         return result;
24     }
25 
26     /**
27      * 把集合转化成指定形式的字符串
28      */
29     public static String formatParameterList(Collection<String> value) {
30         return value == null ? null : StringUtils.collectionToDelimitedString(value, ",");//指定分隔符
31     }
32 
33     /**
34      * 从query的字符串中抽取需要的键值对存入map中
35      * query的形式name=god&password=111&method=up
36      */
37     public static Map<String, String> extractMap(String query) {
38         Map<String, String> map = new HashMap<String, String>();
39         Properties properties = StringUtils.splitArrayElementsIntoProperties(
40                 StringUtils.delimitedListToStringArray(query, "&"), "=");
41         if (properties != null) {
42             for (Object key : properties.keySet()) {
43                 map.put(key.toString(), properties.get(key).toString());
44             }
45         }
46         return map;
47     }
48 
49     /**
50      * 比较两个集合是否相等
51      */
52     public static boolean containsAll(Set<String> target, Set<String> members) {
53         target = new HashSet<String>(target);
54         target.retainAll(members);//取两个集合的交集
55         return target.size() == members.size();
56     }
57 }

 

posted @ 2016-06-13 22:28  godlei  阅读(3789)  评论(0编辑  收藏  举报