Java 8: Reducing a List Into A CSV String
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import org.junit.Test;
public class CSVStreamTest {
@Test
public void listToString() {
List<String> mascots = new ArrayList<>();
mascots.add("duke");
mascots.add("juggy");
String expected = "duke,juggy";
String actual = mascots.stream().
reduce((t, u) -> t + "," + u).
get();
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 = mascots.stream().collect(joining(","));
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
(http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-)
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 #