Sai A Sai A
Updated date Jul 12, 2023
In this blog, we will provide a step-by-step guide to efficiently converting CSV files to lists in Java. With detailed explanations and code examples, the blog explores three different methods: using CSVReader and ArrayList, utilizing Scanner and LinkedList, and leveraging Apache Commons CSV with Vector.
  • 3.4k
  • 0
  • 0

Introduction:

CSV (Comma-Separated Values) files are a popular format for storing tabular data. In Java, it's often necessary to convert CSV files into more accessible formats, such as lists. This tutorial will guide you through different methods to efficiently convert CSV data into lists using Java. Each method will be explained in detail, accompanied by code examples and their respective outputs. By the end of this tutorial, you will have a comprehensive understanding of various approaches for converting CSV files to lists in Java.

Method 1: Using CSVReader and ArrayList

First, we will use the CSVReader class from the OpenCSV library and an ArrayList to store the CSV data. Follow the steps below to convert a CSV file into a list:

  • Add the OpenCSV library to your project dependencies.
  • Import the necessary classes: CSVReader from au.com.bytecode.opencsv.CSVReader and ArrayList from java.util.ArrayList.
  • Create an instance of CSVReader and pass the CSV file's FileReader as a parameter.
  • Initialize an ArrayList to store the converted CSV data.
  • Iterate through each row using a while loop and readNext() method of CSVReader.
  • Inside the loop, split the values of each row using the split() method with the appropriate delimiter.
  • Add the split values to the ArrayList using the add() method.
  • Finally, print the ArrayList to verify the successful conversion.

Here's an example program that demonstrates the conversion:

import au.com.bytecode.opencsv.CSVReader;
import java.io.FileReader;
import java.util.ArrayList;

public class CSVToListConverter {
    public static void main(String[] args) {
        String csvFile = "data.csv"; // Path to your CSV file
        
        try (CSVReader reader = new CSVReader(new FileReader(csvFile))) {
            ArrayList<String[]> csvData = new ArrayList<>();
            String[] line;
            
            while ((line = reader.readNext()) != null) {
                csvData.add(line);
            }
            
            // Print the converted list
            for (String[] row : csvData) {
                for (String value : row) {
                    System.out.print(value + "\t");
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

John    Doe     [email protected]
Jane    Smith   [email protected]
Alex    Johnson [email protected]

Method 2: Utilizing Scanner and LinkedList

In this method, we will use the Scanner class to read the CSV file line by line. Each line will be split into an array of values and added to a LinkedList. This approach is suitable for large CSV files as it avoids reading the entire file at once. Follow the steps below to perform the conversion:

  • Import the necessary classes: Scanner from java.util.Scanner and LinkedList from java.util.LinkedList.
  • Create an instance of Scanner and pass the CSV file's FileReader as a parameter.
  • Initialize a LinkedList to store the converted CSV data.
  • Iterate through each line using a while loop and the hasNextLine() method of Scanner.
  • Inside the loop, split the values of each line using the split() method with the appropriate delimiter.
  • Add the split values to the LinkedList using the add() method.
  • Finally, print the LinkedList to verify the successful conversion.

Here's an example program that demonstrates the conversion:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;

public class CSVToListConverter {
    public static void main(String[] args) {
        String csvFile = "data.csv"; // Path to your CSV file
        
        try {
            Scanner scanner = new Scanner(new File(csvFile));
            LinkedList<String[]> csvData = new LinkedList<>();
            
            while (scanner.hasNextLine()) {
                String[] line = scanner.nextLine().split(",");
                csvData.add(line);
            }
            
            // Print the converted list
            for (String[] row : csvData) {
                for (String value : row) {
                    System.out.print(value + "\t");
                }
                System.out.println();
            }
            
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Output:

John    Doe     [email protected]
Jane    Smith   [email protected]
Alex    Johnson [email protected]

Method 3: Leveraging Apache Commons CSV and Vector

Apache Commons CSV provides a powerful library for CSV parsing. In this method, we will use its CSVParser and Vector classes to convert CSV data into a Vector. Follow the steps below:

  • Add the Apache Commons CSV library to your project dependencies.
  • Import the necessary classes: CSVParser from org.apache.commons.csv.CSVParser and Vector from java.util.Vector.
  • Create an instance of CSVParser and pass the FileReader of the CSV file as a parameter.
  • Initialize a Vector to store the converted CSV data.
  • Iterate through each record using a for-each loop on the CSVParser.
  • Inside the loop, split the values of each record using the get() method of CSVRecord.
  • Add the split values to the Vector using the addElement() method.
  • Finally, print the Vector to verify the successful conversion.

Here's an example program that demonstrates the conversion:

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.FileReader;
import java.util.Vector;

public class CSVToListConverter {
    public static void main(String[] args) {
        String csvFile = "data.csv"; // Path to your CSV file
        
        try (CSVParser parser = new CSVParser(new FileReader(csvFile), CSVFormat.DEFAULT)) {
            Vector<String[]> csvData = new Vector<>();
            
            for (CSVRecord record : parser) {
                String[] values = new String[record.size()];
                
                for (int i = 0; i < record.size(); i++) {
                    values[i] = record.get(i);
                }
                
                csvData.addElement(values);
            }
            
            // Print the converted list
            for (String[] row : csvData) {
                for (String value : row) {
                    System.out.print(value + "\t");
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

John    Doe     [email protected]
Jane    Smith   [email protected]
Alex    Johnson [email protected]

Conclusion:

In this tutorial, we explored three different methods for efficiently converting CSV files into lists in Java. We used the CSVReader class from the OpenCSV library, the Scanner class with LinkedList, and leveraged Apache Commons CSV with Vector. 

Comments (0)

There are no comments. Be the first to comment!!!