Skip to content
Advertisement

How to convert a CSV file to List<Map>

I have a CSV file which has a header in the first line. I want to convert it to List<Map<String, String>>, where each Map<String, String> in the list represents a record in the file. The key of the map is the header and the value is the actual value of the field. What I have so far:

JavaScript

What further operations can I perform on recordStream so that I can transform it to List<Map<String, String>>?

Sample CSV file is:

JavaScript

Finally all these Maps need to be collected to a List.

Advertisement

Answer

The following will work. The header line is retrieved by calling readLine directly on the BufferedReader and by splitting around ,. Then, the rest of the file is read: each line is split around , and mapped to a Map with the corresponding header.

JavaScript

A very important note here is that BufferedReader.lines() does not return a fresh Stream when it is called: we must not skip 1 line after we read the header since the reader will already have advanced to the next line.

As a side note, I used a try-with-resources construct so that the BufferedReader can be properly closed.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement