How to convert List into comma separated string in Java

In this blog post, we will explore how to convert a List to/from a comma-delimited string.

The post covers the following examples:

  • Converting a list of custom objects into a comma-separated string.
  • Converting a List of Strings/Long/Integers into a comma-separated string.

How to Convert a List of Custom Objects into a Comma-Separated String

Converting a list of objects into comma-separated strings can be achieved through various approaches. In this tutorial, we’ll explore methods for converting a list of custom Java objects into a comma-delimited string.

Consider the following example of a User class:

package com.company;

public class User {
    private Integer id;
    private String name;

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Let’s populate a list with instances of the User class:

        List<User> users = new ArrayList<User>();
        User user1 = new User (1,"Eric");

        User user2 = new User (2,"John");
        User user3 = new User (3,"Ram");

        users.add(user1);
        users.add(user2);
        users.add(user3);

Using for loop

The traditional for loop can be used to iterate through the list, appending each object’s name to a StringBuilder with a comma delimiter. Afterward, the last comma is removed.

Here is the sequence of steps

  • Create a String builder object
  • use forEach loop to iterate each object
  • append object name and comma delimiter
  • Convert StringBuilder to String using toString() method
  • As we have a comma added to the last string.
  • Remove the last comma using the substring method

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

public class Main {

    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();
        User user1 = new User (1,"Eric");

        User user2 = new User (2,"John");
        User user3 = new User (3,"Ram");

        users.add(user1);
        users.add(user2);
        users.add(user3);
        StringBuilder sb = new StringBuilder();

        for(User user:users){
            sb.append(user.getName()).append(",");
        }
        String commaDelimeterString=sb.toString();
        if( commaDelimeterString.length() > 0 )
            commaDelimeterString = commaDelimeterString.substring(0, commaDelimeterString.length() - 1);


        System.out.println(commaDelimeterString);

    }
}

Using java8 streams

With Java 8 streams, you can achieve the same result more succinctly. The map function extracts the names, and the Collectors.joining method handles the concatenation with commas.

You can check the below tutorials java8 streams

Here is a sequence of steps

  • list object stream is called using the stream() method
  • Iterate each object using the map method and lambda expression
  • get object email in a lambda expression
  • java.util.stream.Collectors method joining uses a comma delimiter and returns the string comma delimiter using a reducer called collect.

here is a complete example

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

public class Main {

    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();
        User user1 = new User (1,"Eric");
        User user2 = new User (2,"John");
        User user3 = new User (3,"Ram");

        users.add(user1);
        users.add(user2);
        users.add(user3);
        String nameSeparatedString = users.stream().map(user->user.getName())
                .collect(Collectors.joining(","));
        System.out.println(nameSeparatedString);

    }
}

Output:

Eric,John, Ram

Convert a List of strings into a comma-separated string

In these tutorials, We will see how to convert a primitive list of String, Integer, and Long into delimited separated strings.

To convert a primitive list of strings into a comma-separated string, you have several options:

apache commons StringUtils join method

This is easy and simple to convert a string list to comma-separated strings.

If you have the Apache Commons library in your project, the StringUtils.join method simplifies the process:

The same method is available in Apache commons-lang module also i.e org.apache.commons.lang3.StringUtils

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

public class Main {

    public static void main(String[] args) {
        List<String> strList = new ArrayList<>();
        strList.add("one");
        strList.add("two");
        strList.add("three");
        strList.add("four");
        String delimetedCommaString=StringUtils.join(strList, ',');
        System.out.println(delimetedCommaString);
    }
}

Output

one,two, three,four

Spring framework to convert a List of Integer into a comma-separated string

For Spring Framework users, the StringUtils.arrayToDelimitedString method is available in the org.springframework.util package:

This class has arrayToDelimitedString method

Here is the syntax of the method

public static String arrayToDelimitedString(@Nullable
                                            Object[] arr,
                                            String delim)

Here is an example of converting list of integers into a comma-separated string Code

import java.util.ArrayList;
import java.util.List;
import org.springframework.util.StringUtils;

public class Main {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(12);
        list.add(14);
        list.add(50);
        String delimetedCommaString=arrayToDelimitedString(list, ',');
        System.out.println(delimetedCommaString);
    }
}

These methods offer convenient ways to convert lists into comma-separated strings based on your needs.