Join List Strings with Commas in Java

1. Introduction

Joining a list of strings with a delimiter, such as a comma, is a common task in Java programming. This can be particularly useful for creating a single string from a collection of items, such as when preparing data for display or output. Java provides several ways to accomplish this, and this tutorial will demonstrate using the String.join() method introduced in Java 8.

Key Points

- String.join() allows joining elements of an array or iterable with a specified delimiter.

- It is a static method of the String class, making it very convenient for joining strings.

- This method is ideal for joining string lists quickly and efficiently without using loops.

2. Program Steps

1. Create a list of strings.

2. Use String.join() to concatenate the list elements with commas.

3. Print the result.

3. Code Program

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

public class JoinStringsExample {
    public static void main(String[] args) {
        // Create a list of strings
        List<String> items = Arrays.asList("Apple", "Banana", "Cherry", "Date");

        // Join the list items with a comma
        String result = String.join(", ", items);

        // Print the joined string
        System.out.println(result);
    }
}

Output:

Apple, Banana, Cherry, Date

Explanation:

1. List<String> items = Arrays.asList("Apple", "Banana", "Cherry", "Date");: Creates a list of strings using Arrays.asList().

2. String result = String.join(", ", items);: Uses the String.join() method to concatenate the elements of the list items with a comma followed by a space as the delimiter.

3. System.out.println(result);: Prints the concatenated string. This shows all the elements from the list items joined into a single string separated by commas.


Comments