List<Integer>与String之间的转换

发布时间 2023-11-27 16:30:00作者: xiaobaibao

1.List<Integer>转换成一个使用逗号隔开的字符串

String str = list.stream() // 将int表转换成一个流,流中的数据与表中数据一样
          .map(Objects::toString) // 将流中的每一个数据转换成String后返回一个新的流
          .collect(Collectors.joining(",")); // 以逗号隔开

2.将上面的字符串再转换回去

List<Integer> list = Arrays.stream(str.split(",")) // 以逗号为分隔符,将字符串str分割成一个字符串数组后存放在新建的流中
    .map(Integer::parseInt) // 将流中的每一个数据进行数据转换
.collect(Collectors.toList()); // 将流中的元素收集到一个列表中,返回一个List<Integer>对象