Java 实现 List<String> 与 String 互转

在 Java 开发过程中,有时需要将 List<String> 转为 String 存储,后续使用时再还原回去。此时就需要 Java 实现 List<String> 与 String 互转。以下是一种互转方式。

采用如下工具包实现。

xml 复制代码
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Java 代码示例如下。

java 复制代码
    public static void main(String[] args) {
        List<String> testList = new ArrayList<>();
        testList.add("testStr1");
        testList.add("testStr2");
        System.out.println(testList);

        // List<String> 转 String
        String resStr = StringUtils.join(testList, ",");
        System.out.println(resStr);

        // String 转 List<String>
        List<String> resList = Arrays.asList(resStr.split(","));
        System.out.println(resList);
        for (String str : resList) {
            System.out.println(str);
        }
    }

最终运行结果如下所示。

xml 复制代码
[testStr1, testStr2]
testStr1,testStr2
[testStr1, testStr2]
testStr1
testStr2
相关推荐
AM越.1 小时前
Java设计模式详解--装饰器设计模式(含uml图)
java·设计模式·uml
5980354151 小时前
【java工具类】小数、整数转中文大写
android·java·开发语言
JIngJaneIL1 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
吃喝不愁霸王餐APP开发者2 小时前
Java后端服务在对接全国性霸王餐API时的多数据中心部署与就近调用策略
java·开发语言
从心归零2 小时前
springboot-jpa的批量更新方法
java·spring boot·spring
这周也會开心2 小时前
128陷阱,==与equals区别
java·开发语言
TAEHENGV3 小时前
回收站模块 Cordova 与 OpenHarmony 混合开发实战
android·java·harmonyos
a努力。3 小时前
宇树Java面试被问:方法区、元空间的区别和演进
java·后端·面试·宇树科技
2501_916766543 小时前
【面试题1】128陷阱、==和equals的区别
java·开发语言
a程序小傲4 小时前
蚂蚁Java面试被问:注解的工作原理及如何自定义注解
java·开发语言·python·面试