title: Best way to populate a user defined object using the values of string array
body: <p>I am reading two different csv files and populating data into two different objects. I am splitting each line of csv file based on regex(regex is different for two csv files) and populating the object using each data of that array which is obtained by splitting each line using regex as shown below:</p>
  
  <pre><code>public static &lt;T&gt; List&lt;T&gt; readCsv(String filePath, String type) {
  List&lt;T&gt; list = new ArrayList&lt;T&gt;();
      try {
          File file = new File(filePath);
          FileInputStream fileInputStream = new FileInputStream(file);
          InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
          BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
          list = bufferedReader.lines().skip(1).map(line -&gt; {
              T obj = null;
              String[] data = null;
              if (type.equalsIgnoreCase("Student")) {
                  data = line.split(",");
                  ABC abc = new ABC();
                  abc.setName(data[0]);
                  abc.setRollNo(data[1]);
                  abc.setMobileNo(data[2]);
                  obj = (T)abc;
              } else if (type.equalsIgnoreCase("Employee")) {
                  data = line.split("\\|");
                  XYZ xyz = new XYZ();s
                  xyz.setName(Integer.parseInt(data[0]));
                  xyz.setCity(data[1]);
                  xyz.setEmployer(data[2]);
                  xyz.setDesignation(data[3]);
                  obj = (T)xyz;
              }
  
              return obj;
          }).collect(Collectors.toList());} catch(Exception e) {
  
      }}
  </code></pre>
  
  <p>csv files are as below:
  i. csv file to populate ABC object:</p>
  
  <pre><code>Name,rollNo,mobileNo
  Test1,1000,8888888888
  Test2,1001,9999999990
  </code></pre>
  
  <p>ii. csv file to populate XYZ object</p>
  
  <pre><code>Name|City|Employer|Designation
  Test1|City1|Emp1|SSE
  Test2|City2|Emp2|
  </code></pre>
  
  <p>The issue is there can be a missing data for any of the above columns in the csv file as shown in the second csv file. In that case, I will get ArrayIndexOutOfBounds exception.
  Can anyone let me know what is the best way to populate the object using the data of the string array?</p>
  
  <p>Thanks in advance.</p>