Java: Set String List 互转

本文介绍了如何在Java中将Set转换为String,将String转换为List,以及Set与List之间的相互转换,包括具体的代码实现和输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java: Set String List 互转


1.Code

import java.util.*;

public class Main {

    public static void main(String[] args) {

        //List 转成 Set
        System.out.println("-------List 转成 Set--------");
        List<String> appIdList = new ArrayList<>();
        appIdList.add("100001");
        appIdList.add("100002");
        appIdList.add("100003");
        appIdList.add("100003");
        System.out.println("appIdList: "+appIdList);

        Set<String> appIdSet = new HashSet<>(appIdList);
        System.out.println("appIdSet: "+appIdSet);
        System.out.println();

        //Set 转成 以逗号分隔的String
        System.out.println("-------Set 转成 以逗号分隔的String--------");
        System.out.println("appIdSet: "+appIdSet);
        String strAppId = String.join(",", appIdSet);
        System.out.println("strAppId: "+strAppId);
        System.out.println();

        //以逗号分隔的String 转成 Set
        System.out.println("-------以逗号分隔的String 转成 Set--------");
        Set<String> idsSet = new HashSet<>();
        System.out.println("strAppId: "+strAppId);
        idsSet.addAll(Arrays.asList(strAppId.trim().split(",")));
        System.out.println("idsSet: "+idsSet);
    }
}

2.Output

-------List 转成 Set--------
appIdList: [100001, 100002, 100003, 100003]
appIdSet: [100001, 100002, 100003]

-------Set 转成 以逗号分隔的String--------
appIdSet: [100001, 100002, 100003]
strAppId: 100001,100002,100003

-------以逗号分隔的String 转成 Set--------
strAppId: 100001,100002,100003
idsSet: [100001, 100002, 100003]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值