java中带英文逗号","的字符串与List数组之间的相互转换
一、Java中带英文逗号","的字符串转化为List列表
// 将带英文逗号","字符串转换为List<T>
String str = "aaa,bbb,ccc,ddd";
List<String> strList = Arrays.asList(str.split(","));
System.out.println("字符串转化为列表:");
for (int i = 0; i < strList.size(); i++) {
System.out.print(strList.get(i)+" ");
}
输出为:
数组转化为列表:
aaa bbb ccc ddd
上述代码可以分为两部分:
// 将带英文逗号","字符串转换为数组
String str = "aaa,bbb,ccc,ddd";
String[] array = str.split(",");
// 将带英文逗号","字符串转换为List<T>
// String[] array = {"aaa“,”bbb“,”ccc“,”ddd"};
List<String> strList = Arrays.asList(array);
String.split(",")方法
Arrays.asList(array)方法——Arrays为java.util.Arrays
如果字符串str为空则该转换方法会出现异常
例如:但获取数据库中这样为空的数据会出现异常
所以需要进行判断字符串str是否为空白数据
我建议用这个方法:StringUtils.isBlank(str);——StringUtils为org.apache.commons.lang3.StringUtils
该方法可以判断字符串是否为空白,空白的定义为
1)为null
2)为不可见字符(如空格)
3)""
源码为:
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs != null && (strLen = cs.length()) != 0) {
for(int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
二、Java中String类型的List列表转化为带英文逗号","的字符串
// 将List<T>转换为带英文逗号","字符串
List<String> strList = {"aaa“,”bbb“,”ccc“,”ddd"};
String str= StringUtils.join(strList, ",");
System.out.println("列表转化为字符串:");
System.out.print("str" = str);
输出为:
列表转化为字符串:
str = aaa,bbb,ccc,ddd
该方法:StringUtils.join(strList, “,”);——StringUtils为org.apache.commons.lang3.StringUtils
第一个参数是传入一个任意类型数组或集合,第二个参数是拼接符