Java: Set String List 互转

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]
经验分享 程序员 微信小程序 职场和发展