尝试使用 Apache Common CSV 读取 CSV 文件时出现重复

Getting Duplicate while trying to read CSV file with Apache Common CSV

我有一个 class 尝试使用 Apache Common CSV 读取 CSV 文件,到目前为止我的代码工作正常,只是没有得到预期的结果。 我的代码显示 csv 文件中第二列的副本,如下所示:

support@gmail.com
google
google.com
support@gmail.com
google
tutorialspoint
info@tuto.com
google

我的 CSV 文件

Name,User Name,Password
google.com,support@gmail.com,google
tutorialspoint,info@tuto.com,google

我希望得到这样的东西:

google.com
support@gmail.com
google
tutorialspoint
info@tuto.com
google

这是我使用 Apache CSV 解析 csv 的块

public List<String> readCSV(String[] fields) {
        // HERE WE START PROCESSING THE READ CSV CONTENTS
        List<String> contents = new ArrayList<String>();
        FileReader fileReader = null;
        CSVParser csvFileParser = null;

        // HERE WE START PROCESSING
        if(fields!=null){
            //Create the CSVFormat object with the header mapping
            CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);

            try {

                //Create a new list of student to be filled by CSV file data
                List<String> content=new ArrayList<String>();

                //initialize FileReader object
                fileReader = new FileReader(FilePath);

                //initialize CSVParser object
                csvFileParser = new CSVParser(fileReader, csvFileFormat);

                //Get a list of CSV file records
                List<CSVRecord> csvRecords = csvFileParser.getRecords(); 

                //Read the CSV file records starting from the second record to skip the header
                for (int i = 1; i < csvRecords.size(); i++) {
                    CSVRecord record = csvRecords.get(i);
                    //Create a new student object and fill his data
                    for(int j=0; j<fields.length; j++){
                        content.add(record.get(fields[j]));
                    }
                    // Here we submit to contents
                    contents.addAll(content);
                    System.out.println(contents.size());
                } // end of loop
            } 
            catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fileReader.close();
                    csvFileParser.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
            // Here we return
            return contents;
        }

我无法弄清楚这里缺少什么,欢迎任何帮助。

原因是您要在每次迭代中添加字符串列表 content

                contents.addAll(content);

在每次迭代中清除 content 或仅更改

                    content.add(record.get(fields[j]));

                    contents.add(record.get(fields[j]));

并删除

                contents.addAll(content);