在 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.