在 Java 中将一组字符串转换为一个逗号分隔的字符串


首先,我们创建一个包含字符串值的一个集合 -

Set<String>set = new HashSet<>(Arrays.asList("One", "Two", "Three", "Four", "Five", "Six"));

现在,使用 String.join() 将其转换为一个逗号分隔的字符串 -

String str = String.join(", ", set);

示例

以下是将在 Java 中将一组字符串转换为一个逗号分隔字符串的程序 -

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      Set<String>set = new HashSet<>(Arrays.asList("One", "Two", "Three", "Four", "Five", "Six"));
      System.out.println("Set = " + set);
      String str = String.join(", ", set);
      System.out.println("Comma separated String: "+ str);
   }
}

输出

Set = [Five, Six, One, Four, Two, Three]
Comma separated String: Five, Six, One, Four, Two, Three

更新于: 2019 年 9 月 25 日

864 次浏览

启动你的 职业

完成课程获得认证

开始
广告
© . All rights reserved.