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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Proper Java Exception Handling
  • Generics in Java and Their Implementation
  • A Complete Guide on How to Convert InputStream to String In Java
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)

Trending

  • Spring Authentication With MetaMask
  • Writing Reusable SQL Queries for Your Application With DbVisualizer Scripts
  • How to Migrate Vector Data from PostgreSQL to MyScale
  • An Introduction to Build Servers and Continuous Integration
  1. DZone
  2. Data Engineering
  3. Data
  4. Converting a List into Comma Separated Value String in Java

Converting a List into Comma Separated Value String in Java

Mohamed Sanaulla user avatar by
Mohamed Sanaulla
·
May. 13, 13 · Tutorial
Like (0)
Save
Tweet
Share
138.63K Views

Join the DZone community and get the full member experience.

Join For Free

We all have at least once in our coding life time done this: “Concatenate the elements of a List into a comma separated string”. And each time we have spent some time figuring out how to do it or sometimes we copy the code from a previous implementation. Lets see how we can implement this scenario:


public class ListToCommaValues {

  public static void main(String[] args) {

    //List of numbers we want to concatenate
    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7);

    //The string builder used to construct the string
    StringBuilder commaSepValueBuilder = new StringBuilder();

    //Looping through the list
    for ( int i = 0; i< numbers.size(); i++){
      //append the value into the builder
      commaSepValueBuilder.append(numbers.get(i));

      //if the value is not the last element of the list
      //then append the comma(,) as well
      if ( i != numbers.size()-1){
        commaSepValueBuilder.append(", ");
      }
    }
    System.out.println(commaSepValueBuilder.toString());

  }

}



he output would be: 1, 2, 3, 4, 5, 6, 7. Its not rocket science, but just too much verbose and clumsy to write.

You all must be wondering the purpose of writing this article or taking up this scenario. At the Great Indian Developer Conference today Venkat Subramaniam was giving a talk on Design patterns in Modern JVM languages (Groovy, Scala) and mentioned about this scenario and also showed some code in Scala, Groovy and he also mentioned about Java 8. And bang I got an idea to blog about this and here is the same in front of you all.

Lets see how the same can be done in Java 8:


//Java 8 way to concatenate the list of numbers
public class ListToCommaValuesJava8 {

  public static void main(String[] args) {

    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7);

    System.out.println(numbers.stream()
        .map(number -> String.valueOf(number))
        .collect(toStringJoiner(", ")));
  }
}



And the output again would be: 1, 2, 3, 4, 5, 6, 7. The above code is less verbose and much easier to read than the one shown in the beginning. If you are left wondering about stream(), collect() I would recommend you to read a similar and more detailed post using the same.

Let me explain the above single line of code:
map() – Takes in a lambda expression which accepts an argument and returns some value(this is an implementation of java.util.Function interface). In the example above the lambda expression accepts an integer and converts it into a string.

toStringJoiner() – It is a static method in Collectors class and returns aCollector which embeds the logic to use the elements of the stream and combine them into a new StringJoiner instance using the separator passed to the Collector.

StringJoiner- From the Javadoc: StringJoiner is used to construct a sequence of characters separated by an infix delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. In the above example we are making use of the infix delimiter.





Java (programming language) Data Types Strings

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Proper Java Exception Handling
  • Generics in Java and Their Implementation
  • A Complete Guide on How to Convert InputStream to String In Java
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: