Maciej Rumianowski's Weblog 

Apache Commons CSV with Java 8 Streams

by Maciej Rumianowski


Posted on Wednesday Nov 18, 2015 at 08:56PM in Code in Practice


Apache Commons CSV java library provides utility classes to read and write csv files. It provides two ways of reading a file. First by loading whole document to memory and returning a list

Reader in = new StringReader("a;b\nc;d");
CSVParser parser = new CSVParser(in, CSVFormat.EXCEL);
List list = parser.getRecords();

source: http://commons.apache.org/proper/commons-csv/archives/1.2/apidocs/index.html

Second by iterating over the lines.

File csvData = new File("/path/to/csv");
CSVParser parser = CSVParser.parse(csvData, CSVFormat.RFC4180);
for (CSVRecord csvRecord : parser) {
...
}

source: http://commons.apache.org/proper/commons-csv/archives/1.2/apidocs/index.html

Now for both ways can be used with Streams API

Reader in = new StringReader("a;b\nc;d");
CSVParser parser = new CSVParser(in, CSVFormat.EXCEL);
List list = parser.getRecords().stream().collect(toList());

File csvData = new File("/path/to/csv");
CSVParser parser = CSVParser.parse(csvData, CSVFormat.RFC4180);
StreamSupport.stream(parser.spliterator(), false).collect(toList());

The spliterator() is a new method of Iterable interface which is a default method, so that all the old code implementing the interface can use it. Without a default method CSVParser class of commons-csv would fail to compile when using java 8 jdk.



Comments:

A motivating discussion is worth comment. I believe that you should write more on this subject matter, it might not be a taboo matter but generally people don’t discuss these topics. To the next! Many thanks!!

Posted by Dissertation writing service on October 05, 2017 at 10:00 AM GMT #


Leave a Comment

HTML Syntax: NOT allowed