將字串列表轉換為 Java 中的逗號分隔字串


首先,假設以下為我們的字串列表 −

List<String> myList = new ArrayList<>(Arrays.asList("One", "Two", "Three", "Four"));

現在,使用 String.join() 將其轉換為逗號分隔字串

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

示例

以下是將 Java 中的字串列表轉換為逗號分隔字串的程式 −

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      List<String> myList = new ArrayList<>(Arrays.asList("One", "Two", "Three", "Four"));
      System.out.println("List = " + myList);
      // comma separated
      String str = String.join(", ", myList);
      System.out.println("String (Comma Separated) = " + str);
   }
}

輸出

List = [One, Two, Three, Four]
Comma separated String: One, Two, Three, Four

更新日期: 25-Sep-2019

485 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.