标题关于集合list去除两端[]中括号;String类型字符串转换成集合
1、去除集合中括号
方法一:org.apache.commons.lang3.StringUtils.strip()方法
java
public static void main(String[] args) {
List<Integer> longString = new ArrayList<>();
longString.add(1);
longString.add(2);
longString.add(3);
longString.add(4);
longString.add(5);
longString.add(6);
System.out.println(org.apache.commons.lang3.StringUtils.strip(String.valueOf(longString),"[]"));
}
方法二:遍历集合,字符串追加
java
public static void main(String[] args) {
List<Integer> longString = new ArrayList<>();
longString.add(1);
longString.add(2);
longString.add(3);
longString.add(4);
longString.add(5);
longString.add(6);
StringBuffer stringBuffer = new StringBuffer();
longString.forEach(s->{
stringBuffer.append(s).append(",");
});
String substring = stringBuffer.substring(0, stringBuffer.length() - 1);
System.out.println(longString);
System.out.println(substring);
}
2、String类型字符串,转换成集合类型
方法一:Collections.singletonList()方法
java
public static void main(String[] args) {
String str = "1,2,3,4,5,6";
System.out.println(java.util.Collections.singletonList(str));
}
方法二:Arrays.asList()方法
java
public static void main(String[] args) {
String str = "1,2,3,4,5,6";
System.out.println( java.util.Arrays.asList(str.split(",")));
}
方法三:Arrays.stream()转换成指定类型集合
java
public static void main(String[] args) {
String longs = "1,2,3,4,5";
List<Long> longList =Arrays.stream(longs .split(",")).map(s->Long.parseLong(s.trim())).collect(Collectors.toList());
System.out.println(longList);
}
总结
1:集合转String
- org.apache.commons.lang3.StringUtils.strip()方法
- 遍历集合,字符串追加
2:string转集合
- Collections.singletonList()方法
- Arrays.asList()方法
- Arrays.stream()转换成指定类型集合
end--------------------------------------------