DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Functional Approach To String Manipulation in Java
  • The Long Road to Java Virtual Threads
  • A Complete Guide on How to Convert InputStream to String In Java
  • Express Hibernate Queries as Type-Safe Java Streams

Trending

  • Integration Isn’t a Task — It’s an Architectural Discipline
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • Designing a Java Connector for Software Integrations
  1. DZone
  2. Coding
  3. Java
  4. Convert a List to a Comma-Separated String in Java 8

Convert a List to a Comma-Separated String in Java 8

This quick tutorial shows you how to use streams in Java to convert the contents of a list to a comma-separated string in Java 8.

By 
Mario Pio Gioiosa user avatar
Mario Pio Gioiosa
·
Updated Jun. 29, 16 · Tutorial
Likes (24)
Comment
Save
Tweet
Share
528.5K Views

Join the DZone community and get the full member experience.

Join For Free

Converting a List<String> to a String with all the values of the List comma separated in Java 8 is really straightforward. Let’s have a look how to do that.

In Java 8

We can simply write String.join(..), pass a delimiter and an Iterable and the new StringJoiner will do the rest:

List<String> cities = Arrays.asList("Milan", 
                                    "London", 
                                    "New York", 
                                    "San Francisco");

String citiesCommaSeparated = String.join(",", cities);

System.out.println(citiesCommaSeparated);

//Output: Milan,London,New York,San Francisco

If we are working with stream we can write as follow and still have the same result:

String citiesCommaSeparated = cities.stream()
                                    .collect(Collectors.joining(","));


System.out.println(citiesCommaSeparated);

//Output: Milan,London,New York,San Francisco

Note: you can statically import java.util.stream.Collectors.joining if you prefer just typing "joining".

In Java 7

For old times' sake, let’s have a look at the Java 7 implementation:

private static final String SEPARATOR = ",";

public static void main(String[] args) {
  List<String> cities = Arrays.asList(
                                "Milan", 
                                "London", 
                                "New York", 
                                "San Francisco");

  StringBuilder csvBuilder = new StringBuilder();

  for(String city : cities){
    csvBuilder.append(city);
    csvBuilder.append(SEPARATOR);
  }

  String csv = csvBuilder.toString();
  System.out.println(csv);

  //OUTPUT: Milan,London,New York,San Francisco,

  //Remove last comma
  csv = csv.substring(0, csv.length() - SEPARATOR.length());

  System.out.println(csv);

  //OUTPUT: Milan,London,New York,San Francisco
}

As you can see it’s much more verbose and easier to make mistakes like forgetting to remove the last comma. You can implement this in several ways—for example by moving the logic that removes the last comma to inside the for-loop—but no implementation will be so explicative and easy to understand as the declarative solution expressed in Java 8.

Focus should be on what you want to do—joining a List of String—not on how.

Java 8: Manipulate String Before Joining

If you are using Stream, it's really straightforward manipulate your String as you prefer by using map() or cutting some String out by using filter().  I’ll cover those topics in future articles. Meanwhile, this a straightforward example on how to transform the whole String to upper-case before joining.

Java 8: From List to Upper-Case String Comma Separated

String citiesCommaSeparated = cities.stream()
                                    .map(String::toUpperCase)
                                    .collect(Collectors.joining(","));

//Output: MILAN,LONDON,NEW YORK,SAN FRANCISCO

If you  want to find out more about stream, I strongly suggest this cool video from Venkat Subramaniam.

Let’s Play

The best way to learn is playing! Copy this class with all the implementations discussed and play with that. There is already a small test for each of them.

package net.reversecoding.examples;

import static java.util.stream.Collectors.joining;
import static org.junit.Assert.assertEquals;

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

import org.junit.Test;

public class CsvUtil {
 private static final String SEPARATOR = ",";


 public static String toCsv(List < String > listToConvert) {
  return String.join(SEPARATOR, listToConvert);
 }

 @Test
 public void toCsv_csvFromListOfString() {
  List < String > cities = Arrays.asList(
   "Milan", "London", "New York", "San Francisco");

  String expected = "Milan,London,New York,San Francisco";

  assertEquals(expected, toCsv(cities));
 }


 public static String toCsvStream(List < String > listToConvert) {
  return listToConvert.stream()
   .collect(joining(SEPARATOR));
 }

 @Test
 public void toCsvStream_csvFromListOfString() {
  List < String > cities = Arrays.asList(
   "Milan", "London", "New York", "San Francisco");

  String expected = "Milan,London,New York,San Francisco";

  assertEquals(expected, toCsv(cities));
 }

 public static String toCsvJava7(List < String > listToConvert) {
  StringBuilder csvBuilder = new StringBuilder();

  for (String s: listToConvert) {
   csvBuilder.append(s);
   csvBuilder.append(SEPARATOR);
  }

  String csv = csvBuilder.toString();

  //Remove last separator
  if (csv.endsWith(SEPARATOR)) {
   csv = csv.substring(0, csv.length() - SEPARATOR.length());
  }

  return csv;
 }

 @Test
 public void toCsvJava7_csvFromListOfString() {
  List < String > cities = Arrays.asList(
   "Milan", "London", "New York", "San Francisco");

  String expected = "Milan,London,New York,San Francisco";

  assertEquals(expected, toCsvJava7(cities));
 }


 public static String toUpperCaseCsv(List < String > listToConvert) {
  return listToConvert.stream()
   .map(String::toUpperCase)
   .collect(joining(SEPARATOR));
 }

 @Test
 public void toUpperCaseCsv_upperCaseCsvFromListOfString() {
  List < String > cities = Arrays.asList(
   "Milan", "London", "New York", "San Francisco");

  String expected = "MILAN,LONDON,NEW YORK,SAN FRANCISCO";

  assertEquals(expected, toUpperCaseCsv(cities));
 }

}



If you enjoyed this article and want to learn more about Java Streams, check out this collection of tutorials and articles on all things Java Streams.

Java (programming language) Strings Convert (command) Stream (computing)

Published at DZone with permission of Mario Pio Gioiosa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Functional Approach To String Manipulation in Java
  • The Long Road to Java Virtual Threads
  • A Complete Guide on How to Convert InputStream to String In Java
  • Express Hibernate Queries as Type-Safe Java Streams

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: