字符串分隔工具类

66 阅读1分钟
public class SpiltStringUtils {

    /**
     * 逗号分割字符串转为List
     * */
    public static <T> List<T> strToList(String str, Class<T> cls) {
        List<T> res = new ArrayList<>();
        if (StringUtils.isBlank(str)) {
            return res;
        }

        for (String s : str.split(",")) {
            try {
                T obj = JSON.parseObject(s, cls);
                res.add(obj);
            } catch (Exception ignored) {
            }
        }

        return res;
    }

    /**
     * 任意字符分割字符串转为List
     * */
    public static <T> List<T> strToListSeparator(String str, String separator, Class<T> cls) {
        List<T> res = new ArrayList<>();
        if (StringUtils.isBlank(str)) {
            return res;
        }

        for (String s : str.split(separator)) {
            try {
                T obj = JSON.parseObject(s, cls);
                res.add(obj);
            } catch (Exception ignored) {
            }
        }

        return res;
    }
}