List<String>与逗号分隔的字符串互转

将逗号分隔的字符串转换为List

List<String> list = Arrays.asList(str.split(","));
List<String> list = Arrays.asList(StringUtils.split(str, ","));

将逗号连接的字符串转成字符数组:
通过String的split函数可以实现

String aaa = "aa,bb,cc";
String[] split = aaa.split(",");

将list转化为逗号分割的字符串

1.只要不为空,就在后面添加逗号,最后再用subString()函数截取,去掉最后一位的逗号

1.只要不为空,就在后面添加逗号,最后再用subString()函数截取,去掉最后一位的逗号
List<String> test = new ArrayList<>();
String testStrings = "";
test.add("test1");
test.add("test2");
test.add("test3");

for(String object : test){
  if(object != null){
    testStrings +=object + ",";    
  }
}
if(testStrings.length > 0){
  testStrings = testStrings.substring(0,testStrings.length() -1);
}

2.通过StringUtils的join函数直接获取逗号隔开字符串

String str = String.join(",", list);
String str = StringUtils.join(list.toArray(), ",");

3.通过流转换
String newStr = exList.stream().collect(Collectors.joining(“,”)))

public static String parseListToStr(List list) {
    String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
    return result;
}

4.lambda表达式遍历并加入符号

public static String parseListToStr3(List list){
        StringBuffer sb = new StringBuffer();
        list.stream().forEach(str - > { sb .append(str). append(",");});
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
}

将字符串中的字符替换

String newStr = str.replace("需替换的字符", "目标字符");

两个list交集问题

String s1 = "50000,100000,200000,300000,500000,";
String s2 = "10000,30000,50000,100000,";
String[] a1 = s1.split(",");
String[] a2 = s2.split(",");
List<String> list = new ArrayList(Arrays.asList(a1));
list.retainAll(Arrays.asList(a2)); // list 中的就是交集了

//如果仅仅需要知道是否有交集:false: 有交集 ;true: 没有交集
Collections.disjoint(list1,list2)

你可能感兴趣的:(Java,list)