当前位置: 移动技术网 > IT编程>开发语言>Java > 浅谈常用字符串与集合类转换的工具类

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

2019年07月22日  | 移动技术网IT编程  | 我要评论
在项目中,我们经常需要把接收到的字符串转换成对应的集合类保存,或者把集合类转换成字符串以方便传输,这个工具类中封装了几个常用的方法,对于这种转换需求十分方便。 i

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

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();
  }
}

以上这篇浅谈常用字符串与集合类转换的工具类就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网