📌  相关文章
📜  在Java中将 ArrayList 转换为逗号分隔的字符串

📅  最后修改于: 2022-05-13 01:55:05.130000             🧑  作者: Mango

在Java中将 ArrayList 转换为逗号分隔的字符串

要将 ArrayList 转换为逗号分隔的字符串,这些是Java中可用的方法。

  1. 使用 StringBuilder 的 append() 方法
  2. 使用 toString() 方法
  3. 使用 Apache Commons StringUtils 类
  4. 使用流 API
  5. 使用 String 类的 join() 方法

方法一(使用StringBuilder的append()方法): Java中的StringBuilder表示一个可变的字符序列。在下面的示例中,我们使用了 StringBuilder 的 append() 方法。 append 方法用于在现有字符串的最后位置连接或添加一组新字符。

句法 :

public StringBuilder append(char a)

参数:该方法接受单个参数a ,它是要附加其字符串表示的 Char 值。

返回值:该方法在执行追加操作后返回一个字符串对象。

Java
// Java program to Convert ArrayList to Comma Separated
// String 
  
import java.util.ArrayList;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create an ArrayList
        ArrayList geeklist
            = new ArrayList();
  
        // Add elements to ArrayList
        geeklist.add("Hey");
        geeklist.add("Geek");
        geeklist.add("Welcome");
        geeklist.add("to");
        geeklist.add("geeksforgeeks");
        geeklist.add("!");
  
        StringBuilder str = new StringBuilder("");
  
        // Traversing the ArrayList
        for (String eachstring : geeklist) {
  
            // Each element in ArrayList is appended
            // followed by comma
            str.append(eachstring).append(",");
        }
  
        // StringBuffer to String conversion
        String commaseparatedlist = str.toString();
  
        // By following condition you can remove the last
        // comma
        if (commaseparatedlist.length() > 0)
            commaseparatedlist
                = commaseparatedlist.substring(
                    0, commaseparatedlist.length() - 1);
  
        System.out.println(commaseparatedlist);
    }
}


Java
// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.ArrayList;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create an ArrayList
        ArrayList geekcourses
            = new ArrayList();
  
        // Add elements to ArrayList
        geekcourses.add("Data Structures");
        geekcourses.add("Algorithms");
        geekcourses.add("Operating System");
        geekcourses.add("Computer Networks");
        geekcourses.add("Machine Learning");
        geekcourses.add("Databases");
  
        /* toString method returns the output as [Data
           Structure,Algorithms,...] In order to replace
           '[', ']' and spaces with empty strings to get
           comma separated values.*/
  
        String commaseparatedlist = geekcourses.toString();
  
        commaseparatedlist
            = commaseparatedlist.replace("[", "")
                  .replace("]", "")
                  .replace(" ", "");
  
        System.out.println(commaseparatedlist);
    }
}


Java
// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.ArrayList;
import org.apache.commons.collections4.CollectionUtils;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create an ArrayList
        ArrayList geekcourses
            = new ArrayList();
  
        // Add elements to ArrayList
        geekcourses.add("Data Structures");
        geekcourses.add("Algorithms");
        geekcourses.add("Operating System");
        geekcourses.add("Computer Networks");
        geekcourses.add("Machine Learning");
        geekcourses.add("Databases");
  
        /*join method of StringUtils class is used
        which returns a single string along with defined
        separator in every iteration.*/
  
        String commalist
            = StringUtils.join(geekcourses, ",");
        System.out.println(commalist);
    }
}


Java
// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.*;
import java.util.stream.Collectors;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create ArrayList of String
        ArrayList geeklist
            = new ArrayList();
  
        // add elements to ArrayList
        geeklist.add("welcome");
        geeklist.add("to");
        geeklist.add("geeks");
        geeklist.add("for");
        geeklist.add("geeks");
  
        // The collect method is used to return the result
        // of the intermediate operations performed on the
        // stream.
        String str = geeklist.stream().collect(
            Collectors.joining(","));
        System.out.println(str);
    }
}


Java
// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.*;
import java.util.stream.Collectors;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create ArrayList of String
        ArrayList geeklist
            = new ArrayList();
  
        // add elements to ArrayList
        geeklist.add("welcome");
        geeklist.add("to");
        geeklist.add("geeks");
        geeklist.add("for");
        geeklist.add("geeks");
  
        // String.join() is used with a delimiter comma
        // along with the list.
        String str = String.join(",", geeklist);
        System.out.println(str);
    }
}


输出
Hey,Geek,Welcome,to,geeksforgeeks,!

方法 2(使用 toString() 方法):toString()是一个内置方法,它以字符串格式返回给定的值。下面的代码使用 toString() 方法将 ArrayList 转换为 String。该方法返回应用了替换方法并替换指定字符(在本例中为括号和空格)的单个字符串。

句法:

arraylist.toString()

这里,arraylist 是 ArrayList 类的对象。

返回值:它返回数组列表的字符串表示

Java

// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.ArrayList;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create an ArrayList
        ArrayList geekcourses
            = new ArrayList();
  
        // Add elements to ArrayList
        geekcourses.add("Data Structures");
        geekcourses.add("Algorithms");
        geekcourses.add("Operating System");
        geekcourses.add("Computer Networks");
        geekcourses.add("Machine Learning");
        geekcourses.add("Databases");
  
        /* toString method returns the output as [Data
           Structure,Algorithms,...] In order to replace
           '[', ']' and spaces with empty strings to get
           comma separated values.*/
  
        String commaseparatedlist = geekcourses.toString();
  
        commaseparatedlist
            = commaseparatedlist.replace("[", "")
                  .replace("]", "")
                  .replace(" ", "");
  
        System.out.println(commaseparatedlist);
    }
}
输出
DataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases

方法 3(使用 Apache Commons StringUtils 类): Apache Commons 库有一个StringUtils类,为字符串提供实用函数。 join 方法用于将 ArrayList 转换为逗号分隔的字符串。

Java

// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.ArrayList;
import org.apache.commons.collections4.CollectionUtils;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create an ArrayList
        ArrayList geekcourses
            = new ArrayList();
  
        // Add elements to ArrayList
        geekcourses.add("Data Structures");
        geekcourses.add("Algorithms");
        geekcourses.add("Operating System");
        geekcourses.add("Computer Networks");
        geekcourses.add("Machine Learning");
        geekcourses.add("Databases");
  
        /*join method of StringUtils class is used
        which returns a single string along with defined
        separator in every iteration.*/
  
        String commalist
            = StringUtils.join(geekcourses, ",");
        System.out.println(commalist);
    }
}

输出

OutputDataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases

方法四(Using Stream API): Stream API是Java 8中引入的,用于处理对象的集合。在Java中,Collectors 类的 join() 方法用于将字符或字符串数组的各种元素连接到单个字符串对象中。

Java

// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.*;
import java.util.stream.Collectors;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create ArrayList of String
        ArrayList geeklist
            = new ArrayList();
  
        // add elements to ArrayList
        geeklist.add("welcome");
        geeklist.add("to");
        geeklist.add("geeks");
        geeklist.add("for");
        geeklist.add("geeks");
  
        // The collect method is used to return the result
        // of the intermediate operations performed on the
        // stream.
        String str = geeklist.stream().collect(
            Collectors.joining(","));
        System.out.println(str);
    }
}
输出
welcome,to,geeks,for,geeks

方法 5(使用 String join() 方法:我们可以使用Java字符字符串转换为逗号分隔的 String提供的前缀并以提供的后缀结尾。String 类的 join() 方法可用于构造相同的内容。

Java

// Java program to Convert ArrayList to Comma Separated
// String in Java
  
import java.util.*;
import java.util.stream.Collectors;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Create ArrayList of String
        ArrayList geeklist
            = new ArrayList();
  
        // add elements to ArrayList
        geeklist.add("welcome");
        geeklist.add("to");
        geeklist.add("geeks");
        geeklist.add("for");
        geeklist.add("geeks");
  
        // String.join() is used with a delimiter comma
        // along with the list.
        String str = String.join(",", geeklist);
        System.out.println(str);
    }
}
输出
welcome,to,geeks,for,geeks