How to convert a List of String to a comma separated String in Java

In this section, we will show you how to convert a List of String to a comma separated String in Java.

1. List

1.1 Using String.join()

join (CharSequence delimiter, Iterable<? extends CharSequence> elements): This method is useful when we have to join iterable elements. Some of the common Iterables are – List, Set, Queue, and Stack.

import java.util.Arrays;
import java.util.List;

public class Main {

public static void main(String[] args) {

List<String> list = Arrays.
asList("Java","Kotlin","Python","C");
String result = String.join(",", list);

System.out.println(result);
}
}


Console Output:
Java,Kotlin,Python,C


1.2 Stream Collectors.joining()

joining(CharSequence delimiter):We pass a delimiter to get back a Collector, which concatenates the elements separated by the specified delimiter.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

List<String> list = Arrays.
asList("Java","Kotlin","Python","C");
String result = list.stream().
collect(Collectors.joining(","));

System.out.println(result);
}
}


Console Output:
Java,Kotlin,Python,C


2. Custom method to join the String

import java.util.Arrays;
import java.util.List;

public class Main {

public static void main(String[] args) {

List<String> list = Arrays.
asList("Java","Kotlin","Python","C");
String result = join(',',list);
System.out.println(result);
}

private static String join(char separator, List<String> input) {

if (input == null || input.size() <= 0)
{
return "";
}

StringBuilder sb = new StringBuilder();

for (int i = 0; i < input.size(); i++) {
sb.append(input.get(i));
if (i != input.size() - 1) {
sb.append(separator);
}
}
return sb.toString();
}
}


Console Output:
Java,Kotlin,Python,C

More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete