How to read a csv and create a list of maps out of each line?

5.2k views Asked by At

I have a Java class to automate some behaviour on the web, my only problem is that now instead of the static data that I have I need to use the data from the csv.

for example:

this is one of the actions in my automation class:

WebElement supplierAddressField = driver.findElement(By.id("FieldaddressOfSupplierLine"));
        supplierAddressField.sendKeys("hollywood blvd 34");

So now, instead of the static "supplier address" value I want to iterate on each line of the .sendKeys(csvLineMap.get("supplier address"));

Because in each line I dont need all the headers info, this is why I think it will be the best to just create a list of maps, that each map key will be the header of the csv and the value will be the value for this header in a specific line.

this is the structure of the csv:

enter image description here

Please help me to figure this out...thanksss!!

3

There are 3 answers

0
Scott Conway On

Apache Commons CSV

For what you are asking for I would recommend you look at Apache Commons CSV. One of the examples from their User Guide matches very closely with with the examples you are trying

Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
    String lastName = record.get("Last Name");
    String firstName = record.get("First Name");
}
0
Louise On

ok, this might be overly complex for what you want, but I always open csv's as excel files because then you can run down the columns. The code for picking up any column would look like this:

                Workbook w = Workbook.getWorkbook(inputWorkbook);                      
                Sheet sheet = w.getSheet(0);
                nom = sheet.getRows();
                String[][] SheetArray = new String [2][nom];  
                   // change the first number to the number of columns you want, 
                   // or pick up the number same as you did with rows   


                Cell cell;           

                  // GETS DATA FROM SHEET AND RUNS THROUGH WHOLE LOOP BELOW FOR EACH REFERENCE            
                 for(int j =0;j<sheet.getRows();j++) // cycles through rows and loads into 2d array
                    { // start 6
                     cell = sheet.getCell(0, j); <- your column number here
                     cellcont = cell.getContents();                        
                      SheetArray[0][j] = cellcont;

                       // repeat the above block for each column you want

                        } // end 6

you now have a 2d array with all the info in it which you can handle however you want.

wrap the entire thing in a try .. catch.

0
Jeronimo Backes On

With uniVocity-parsers you can parse only the fields you are interested, in any order:

    CsvParserSettings parserSettings = new CsvParserSettings();

    // Let's extract headers
    parserSettings.setHeaderExtractionEnabled(true);

    parserSettings.selectFields("Field 5", "Field 1");

    //Rows will come organized according to your field selection
    List<String[]> allRows = parser.parseAll("path/to/file.csv");

If you prefer, you can easily get a map with the values of all columns:

    CsvParserSettings parserSettings = new CsvParserSettings();
    // Let's extract headers
    parserSettings.setHeaderExtractionEnabled(true);

    // To get the values of all columns, use a column processor
    ColumnProcessor rowProcessor = new ColumnProcessor();
    parserSettings.setRowProcessor(rowProcessor);

    CsvParser parser = new CsvParser(parserSettings);

    //This will kick in our column processor
    parser.parse(new FileReader("path/to/file.csv"));

    //Finally, we can get the column values:
    Map<String, List<String>> columnValues = rowProcessor.getColumnValuesAsMapOfNames();

Have a look. It is faster than any other parser and you can do much more, such as converting the values and generating java beans.

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).