Java List转String,String转List

时间:2025-04-04 13:28:48

Java List转String,String转List

1.采用java8 字符串拼接

// 我比较喜欢这种方法
public static void main(String[] args) {
      List<String> list = Lists.newArrayList();
      list.add("test1");
      list.add("test2");
      list.add("test3");
      String join = String.join(",", list);
      // 输出:test1,test2,test3
      System.out.println(join); 
    }
String str = "a,b,c";
List<String> list1 = Arrays.asList(str.split(",")); //[a, b, c]

2、采用guava的Joiner字符串拼接

public static void main(String[] args) {
     List<String> list = Lists.newArrayList();
     list.add("test4");
     list.add("test5");
     list.add("test6");
     String join = Joiner.on(",").join(list);
     // 输出test4,test5,test6
     System.out.println(join);
    }

3、将list泛型user对象中的某个参数添加到String字符串中

// 查询用户
List<User> users = userService.findAll();
// 设置拼接的list
List<String> stringJoinList = Lists.newArrayList();
// 循环users,将姓名取出来,添加到stringJoinList中
for (User user : users) {
    stringJoinList.add(user.getRealname());
}
// 输出:张三,李四,王五
System.out.println(String.join(",",stringJoinList));

转String

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");

// 方法一
String str1 = StringUtils.join(list, ","); //a,b,c
// 方法二
String str2 = StringUtils.join(list, ""); //abc