简体   繁体   中英

How to make a dynamic list of Objects

Suppose I have a CSV file as:

employees.csv

ID,Name,Role,Salary
1,Pankaj Kumar,CEO,"5,000USD"
2,Lisa,Manager,500USD
3,David,,1000USD

I can parse this to the list of Employee objects as:

Employee.java

package com.journaldev.parser.csv;

public class Employee {

    private String id;
    private String name;
    private String role;
    private String salary;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public String getSalary() {
        return salary;
    }
    public void setSalary(String salary) {
        this.salary = salary;
    }

    @Override
    public String toString(){
        return "ID="+id+",Name="+name+",Role="+role+",Salary="+salary+"\n";
    }
}

But what if I want to make my code so that it can process files with more or less columns, without knowing in advance what their names are:

employees.csv

ID,Name,Role,Salary, dateJoined, sex
1,Pankaj Kumar,CEO,"5,000USD",Jan 05 2014 12:04:01PM,MALE
2,Lisa,Manager,500USD,Feb 11 2012 12:04:01PM, FEMALE
3,David,,1000USD,Jan 02 2013 12:04:01PM, MALE

I would like to make this so that it doesn't matter the number of columns in file. So for each column in file, code creates another element in the list of objects.

The rest of my code:

package openCSV_fileReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
public class OpenCSV_fileReader {

     public static void main(String[] args) throws IOException {

            List<Employee> emps = parseCSVFileAsList();
            System.out.println("**********");
            writeCSVData(emps);
     }
        private static void writeCSVData(List<Employee> emps) throws IOException {
            StringWriter writer = new StringWriter();
            CSVWriter csvWriter = new CSVWriter(writer,'#');
            List<String[]> data  = toStringArray(emps);
            csvWriter.writeAll(data);
            csvWriter.close();
            System.out.println(writer);
        }

        private static List<String[]> toStringArray(List<Employee> emps) {
            List<String[]> records = new ArrayList<String[]>();
            //add header record
            records.add(new String[]{"ID","Name","Role","Salary"});
            Iterator<Employee> it = emps.iterator();
            while(it.hasNext()){
                Employee emp = it.next();
                records.add(new String[]{emp.getId(),emp.getName(),emp.getRole(),emp.getSalary()});
            }
            return records;
        }

        private static List<Employee> parseCSVFileAsList() throws IOException {
            CSVReader reader = new CSVReader(new FileReader("employees.csv"), ',');

            List<Employee> emps = new ArrayList<Employee>();
            //read all lines at once
            List<String[]> records = reader.readAll();

            Iterator<String[]> iterator = records.iterator();
            //skip header row
            iterator.next();

            while(iterator.hasNext()){
                String[] record = iterator.next();
                Employee emp = new Employee();
                emp.setId(record[0]);
                emp.setName(record[1]);
                emp.setRole(record[2]);
                emp.setSalary(record[3]);
                emps.add(emp);
            }

            reader.close();

            System.out.println(emps);
            return emps;
        }     
}

Is this doable? This is where I am having trouble finding a way of doing this.

public class CSVTable {

    private String[][] csvTable = null;

    public CSVTable(int columns)
    {
        csvTable = new String[columns][2];
    }

    public String[][] getCSVTable()
    {
        return this.csvTable;
    }

    public void setCSVTable(String[][] csvTable)
    {
        this.csvTable = csvTable;
    }
}

private static List<Employee> parseCSVFileAsList() throws IOException {
            CSVReader reader = new CSVReader(new FileReader("employees.csv"), ',');

        List<CSVTable> csvObjects = new ArrayList<CSVTable>();
        //read all lines at once
        List<String[]> records = reader.readAll();
        String[] columns = null;
        String[] record = null;
        int length = 0;
        Iterator<String[]> iterator = records.iterator();
        //skip header row

        record = iterator.next();
        length = record.length;
        columns = new String[length];
        for(int i = 0; i < length; i++)
        {
            columns[i] = record[i];
        }


        while(iterator.hasNext()){
            record = iterator.next();
            CSVTable csvTable = new CSVTable(record.length);
            String[][] insertRecord = csvTable.getCSVTable();
            for(int i = 0; i < length; i++)
            {
                insertRecord[i][0] = columns[i];
                insertRecord[i][1] = record[i];
            }
            csvTable.setCSVTable(insertRecord);
            csvObjects.add(csvTable);
        }

        reader.close();

        System.out.println(csvObjects);
        return csvObjects;
    }

I hope this is enough to go by obviously you will have to modify some of your other methods as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM