Mapping CSV to JavaBeans Using OpenCSV - GeeksforGeeks

17 Jul, 2018
OpenCSV provides classes to map CSV file to a list of Java-beans. CsvToBean class is used to map CSV data to JavaBeans. The CSV data can be parsed to a bean, but what is required to be done is to define the mapping strategy and pass the strategy to CsvToBean to parse the data into a bean. HeaderColumnNameTranslateMappingStrategy is the mapping strategy which maps the column id to the java bean property.
First add OpenCSV to the project.For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency>    <groupId>com.opencsv</groupId>    <artifactId>opencsv</artifactId>    <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path.Mapping CSV to JavaBeansMapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap();
        mapping.put("column  id ", "javaBeanProperty");
Then add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy =
 new HeaderColumnNameTranslateMappingStrategy();
        strategy.setType(JavaBeanObject.class);
        strategy.setColumnMapping(mapping);
Create the object of CSVReade and CsvToBean classString csvFilename = "data.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
CsvToBean csv = new CsvToBean();
Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader);

First add OpenCSV to the project.For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency>    <groupId>com.opencsv</groupId>    <artifactId>opencsv</artifactId>    <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path.
For maven project, include the OpenCSV maven dependency in pom.xml file.<dependency>    <groupId>com.opencsv</groupId>    <artifactId>opencsv</artifactId>    <version>4.1</version></dependency>
<dependency>    <groupId>com.opencsv</groupId>    <artifactId>opencsv</artifactId>    <version>4.1</version></dependency>
For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
You can Download OpenCSV Jar and include in your project class path.
Mapping CSV to JavaBeansMapping a CSV to JavaBeans is simple and easy process. Just follow these couple of steps:Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap();
        mapping.put("column  id ", "javaBeanProperty");
Then add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy =
 new HeaderColumnNameTranslateMappingStrategy();
        strategy.setType(JavaBeanObject.class);
        strategy.setColumnMapping(mapping);
Create the object of CSVReade and CsvToBean classString csvFilename = "data.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
CsvToBean csv = new CsvToBean();
Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader);

Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap();
        mapping.put("column  id ", "javaBeanProperty");
Then add all the column id of csv file with their corresponding javabean property.Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy =
 new HeaderColumnNameTranslateMappingStrategy();
        strategy.setType(JavaBeanObject.class);
        strategy.setColumnMapping(mapping);
Create the object of CSVReade and CsvToBean classString csvFilename = "data.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
CsvToBean csv = new CsvToBean();
Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader);

Create a Hashmap with mapping between the column id and bean property.Map mapping = new HashMap();
        mapping.put("column  id ", "javaBeanProperty");
Then add all the column id of csv file with their corresponding javabean property.
Map mapping = new HashMap();
        mapping.put("column  id ", "javaBeanProperty");

Then add all the column id of csv file with their corresponding javabean property.
Create HeaderColumnNameTranslateMappingStrategy object pass mapping hashmap to setColumnMapping method.HeaderColumnNameTranslateMappingStrategy strategy =
 new HeaderColumnNameTranslateMappingStrategy();
        strategy.setType(JavaBeanObject.class);
        strategy.setColumnMapping(mapping);

HeaderColumnNameTranslateMappingStrategy strategy =
 new HeaderColumnNameTranslateMappingStrategy();
        strategy.setType(JavaBeanObject.class);
        strategy.setColumnMapping(mapping);

Create the object of CSVReade and CsvToBean classString csvFilename = "data.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
CsvToBean csv = new CsvToBean();

String csvFilename = "data.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
CsvToBean csv = new CsvToBean();

Call parse method of CsvToBean class and pass HeaderColumnNameTranslateMappingStrategy and CSVReader objects.List list = csv.parse(strategy, csvReader);

List list = csv.parse(strategy, csvReader);

Example: Let’ s convert csv file containing Student data to Student objects having attribute Name, RollNo, Department, Result, Pointer.
StudentData.csv:

name, rollno, department, result, cgpa
amar, 42, cse, pass, 8.6
rohini, 21, ece, fail, 3.2
aman, 23, cse, pass, 8.9
rahul, 45, ee, fail, 4.6
pratik, 65, cse, pass, 7.2
raunak, 23, me, pass, 9.1
suvam, 68, me, pass, 8.2

First create a Student Class with Attributes Name, RollNo, Department, Result, Pointer. Then Create a main class which map csv data to JavaBeans object.
Programs:
Student.javapublic class Student {    private static final long serialVersionUID = 1L;      public String Name, RollNo, Department, Result, Pointer;      public String getName()    {        return Name;    }      public void setName(String name)    {        Name = name;    }      public String getRollNo()    {        return RollNo;    }      public void setRollNo(String rollNo)    {        RollNo = rollNo;    }      public String getDepartment()    {        return Department;    }      public void setDepartment(String department)    {        Department = department;    }      public String getResult()    {        return Result;    }      public void setResult(String result)    {        Result = result;    }      public String getPointer()    {        return Pointer;    }      public void setPointer(String pointer)    {        Pointer = pointer;    }      @Override    public String toString()    {        return "Student [Name=" + Name + ", RollNo=" + RollNo + ",            Department            = " + Department + ",            Result = " + Result                     + ", Pointer=" + Pointer + "]";    }}csvtobean.javaimport java.io.*;import java.util.*;  import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;  public class csvtobean {    public static void main(String[] args)    {          // Hashmap to map CSV data to         // Bean attributes.        Map<String, String> mapping = new                       HashMap<String, String>();        mapping.put("name", "Name");        mapping.put("rollno", "RollNo");        mapping.put("department", "Department");        mapping.put("result", "Result");        mapping.put("cgpa", "Pointer");          // HeaderColumnNameTranslateMappingStrategy        // for Student class        HeaderColumnNameTranslateMappingStrategy<Student> strategy =             new HeaderColumnNameTranslateMappingStrategy<Student>();        strategy.setType(Student.class);        strategy.setColumnMapping(mapping);          // Create castobaen and csvreader object        CSVReader csvReader = null;        try {            csvReader = new CSVReader(new FileReader            ("D:\\EclipseWorkSpace\\CSVOperations\\StudentData.csv"));        }        catch (FileNotFoundException e) {              // TODO Auto-generated catch block            e.printStackTrace();        }        CsvToBean csvToBean = new CsvToBean();          // call the parse method of CsvToBean        // pass strategy, csvReader to parse method        List<Student> list = csvToBean.parse(strategy, csvReader);          // print details of Bean object        for (Student e : list) {            System.out.println(e);        }    }}
Student.javapublic class Student {    private static final long serialVersionUID = 1L;      public String Name, RollNo, Department, Result, Pointer;      public String getName()    {        return Name;    }      public void setName(String name)    {        Name = name;    }      public String getRollNo()    {        return RollNo;    }      public void setRollNo(String rollNo)    {        RollNo = rollNo;    }      public String getDepartment()    {        return Department;    }      public void setDepartment(String department)    {        Department = department;    }      public String getResult()    {        return Result;    }      public void setResult(String result)    {        Result = result;    }      public String getPointer()    {        return Pointer;    }      public void setPointer(String pointer)    {        Pointer = pointer;    }      @Override    public String toString()    {        return "Student [Name=" + Name + ", RollNo=" + RollNo + ",            Department            = " + Department + ",            Result = " + Result                     + ", Pointer=" + Pointer + "]";    }}
public class Student {    private static final long serialVersionUID = 1L;      public String Name, RollNo, Department, Result, Pointer;      public String getName()    {        return Name;    }      public void setName(String name)    {        Name = name;    }      public String getRollNo()    {        return RollNo;    }      public void setRollNo(String rollNo)    {        RollNo = rollNo;    }      public String getDepartment()    {        return Department;    }      public void setDepartment(String department)    {        Department = department;    }      public String getResult()    {        return Result;    }      public void setResult(String result)    {        Result = result;    }      public String getPointer()    {        return Pointer;    }      public void setPointer(String pointer)    {        Pointer = pointer;    }      @Override    public String toString()    {        return "Student [Name=" + Name + ", RollNo=" + RollNo + ",            Department            = " + Department + ",            Result = " + Result                     + ", Pointer=" + Pointer + "]";    }}
csvtobean.javaimport java.io.*;import java.util.*;  import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;  public class csvtobean {    public static void main(String[] args)    {          // Hashmap to map CSV data to         // Bean attributes.        Map<String, String> mapping = new                       HashMap<String, String>();        mapping.put("name", "Name");        mapping.put("rollno", "RollNo");        mapping.put("department", "Department");        mapping.put("result", "Result");        mapping.put("cgpa", "Pointer");          // HeaderColumnNameTranslateMappingStrategy        // for Student class        HeaderColumnNameTranslateMappingStrategy<Student> strategy =             new HeaderColumnNameTranslateMappingStrategy<Student>();        strategy.setType(Student.class);        strategy.setColumnMapping(mapping);          // Create castobaen and csvreader object        CSVReader csvReader = null;        try {            csvReader = new CSVReader(new FileReader            ("D:\\EclipseWorkSpace\\CSVOperations\\StudentData.csv"));        }        catch (FileNotFoundException e) {              // TODO Auto-generated catch block            e.printStackTrace();        }        CsvToBean csvToBean = new CsvToBean();          // call the parse method of CsvToBean        // pass strategy, csvReader to parse method        List<Student> list = csvToBean.parse(strategy, csvReader);          // print details of Bean object        for (Student e : list) {            System.out.println(e);        }    }}
import java.io.*;import java.util.*;  import com.opencsv.CSVReader;import com.opencsv.bean.CsvToBean;import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;  public class csvtobean {    public static void main(String[] args)    {          // Hashmap to map CSV data to         // Bean attributes.        Map<String, String> mapping = new                       HashMap<String, String>();        mapping.put("name", "Name");        mapping.put("rollno", "RollNo");        mapping.put("department", "Department");        mapping.put("result", "Result");        mapping.put("cgpa", "Pointer");          // HeaderColumnNameTranslateMappingStrategy        // for Student class        HeaderColumnNameTranslateMappingStrategy<Student> strategy =             new HeaderColumnNameTranslateMappingStrategy<Student>();        strategy.setType(Student.class);        strategy.setColumnMapping(mapping);          // Create castobaen and csvreader object        CSVReader csvReader = null;        try {            csvReader = new CSVReader(new FileReader            ("D:\\EclipseWorkSpace\\CSVOperations\\StudentData.csv"));        }        catch (FileNotFoundException e) {              // TODO Auto-generated catch block            e.printStackTrace();        }        CsvToBean csvToBean = new CsvToBean();          // call the parse method of CsvToBean        // pass strategy, csvReader to parse method        List<Student> list = csvToBean.parse(strategy, csvReader);          // print details of Bean object        for (Student e : list) {            System.out.println(e);        }    }}
Output:
Student [Name=amar, RollNo=42, Department=cse, Result=pass, Pointer=8.6]
Student [Name=rohini, RollNo=21, Department=ece, Result=fail, Pointer=3.2]
Student [Name=aman, RollNo=23, Department=cse, Result=pass, Pointer=8.9]
Student [Name=rahul, RollNo=45, Department=ee, Result=fail, Pointer=4.6]
Student [Name=pratik, RollNo=65, Department=cse, Result=pass, Pointer=7.2]
Student [Name=raunak, RollNo=23, Department=me, Result=pass, Pointer=9.1]
Student [Name=suvam, RollNo=68, Department=me, Result=pass, Pointer=8.2]

Reference: OpenCSV Documentation, CsvTOBean Documentation, MappingStrategy
CSV
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java