Java 8: Reducing a List Into A CSV String

import java.util.ArrayList;
import java.util.List;
import static;
import static org.junit.Assert.*;
import org.junit.Test;

public class CSVStreamTest {

    public void listToString() {
        List<String> mascots = new ArrayList<>();

        String expected = "duke,juggy";
        String actual =
                reduce((t, u) -> t + "," + u).
        assertThat(actual, is(expected));

See you at Java EE Workshops at MUC Airport!


While I share the passion for Java8, consider adding a quote method for your arguments? I've been hit by too many CSV thrown-togethers to ignore them anymore.

Posted by Matti on April 15, 2014 at 12:01 PM CEST #

You could do instead:

String actual =","));

Posted by Michael Nascimento Santos on April 15, 2014 at 02:36 PM CEST #

Hi Adam,
for a Lambda-Example it's a nice. But for solving a problem (and you already use Java 8), I think you can also use String#join

Greetings, Matthias

Posted by Matthias on April 15, 2014 at 06:35 PM CEST #

Why not String.join(",", list)?

Posted by aco on April 16, 2014 at 12:44 AM CEST #

please add "all comments" feed to your blog.

Posted by ali on April 26, 2014 at 07:32 PM CEST #

very good example , i found it really helpful

Posted by Subham on April 29, 2014 at 09:46 PM CEST #

This is a dangerous way to code. Stream.reduce() isn't constrained to execute sequentially, so in theory the elements in your csv string could be returned in any order.

Posted by tsotha on August 09, 2016 at 11:33 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments