tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 CSV > SUPER CSV > Read CSV As List of Maps

Read CSV As List of Maps 

Super CSV is a free library for reading and writing CSV files in Java. We need to have SuperCSV-1.52.jar, spiffy-0.05.jar or later versions in classpath. The following example shows reading a CSV as list of maps using Super CSV. The CSV header name is used as key and column data as value.

File Name  :  
/SuperCSV/config/studs.csv 
name,age,hobby
Sriram,2,Chess
Sudhakar,29,Painting

File Name  :  
com/bethecoder/tutorials/super_csv/tests/ReadCSVAsListOfMaps.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.super_csv.tests;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.supercsv.io.CsvListReader;
import org.supercsv.prefs.CsvPreference;

public class ReadCSVAsListOfMaps {

  /**
   @param args
   @throws IOException 
   */
  public static void main(String[] argsthrows IOException {
    /**
     * Load CSV from classpath
     */
    CsvListReader csvReader = new CsvListReader(new InputStreamReader(
        ReadCSVAsListOfMaps.class.getClassLoader().getResourceAsStream("studs.csv")),
        CsvPreference.STANDARD_PREFERENCE);
    
    //Read CSV Header
    List<String> header = new ArrayList<String>(csvReader.read());
      List<String> rowAsTokens;
      
      //Read the CSV as List of Maps where each Map represents row data
      List<Map<String, String>> rows = new ArrayList<Map<String, String>>();
      Map<String, String> row = null;
      
      while ((rowAsTokens = csvReader.read()) != null) {
        //Create Map for each row in CSV
        row = new HashMap<String, String>();
        
        for (int i = ; i < header.size() ; i ++) {
          row.put(header.get(i), rowAsTokens.get(i));
        }
        
        //add Row map to list of rows
        rows.add(row);
      }
      
      
      //Iterate
      for (Map<String, String> rowMap : rows) {
        System.out.println(rowMap);
      }
      
  }

}
   

It gives the following output,
{age=2, name=Sriram, hobby=Chess}
{age=29, name=Sudhakar, hobby=Painting}


                    Print

   



Books Recommendation

 
 
bl  br