Sai A Sai A
Updated date Jul 26, 2023
In this blog, we will explore how to convert CSV to a List array in java. CSV files are widely used for data storage and exchange, and understanding how to parse them efficiently is essential for many Java developers. We begin with a basic method using BufferedReader and split, gradually advancing to more powerful techniques with the help of popular libraries like Apache Commons CSV and OpenCSV.

Introduction:

Working with CSV (Comma-Separated Values) files is a common task in Java programming. CSV files are widely used for data storage and exchange due to their simplicity and compatibility with various applications. In this blog, we will explore different methods to read and convert CSV data into a List Array in Java

Method 1: Using BufferedReader and Split

In this method, we will use the BufferedReader class to read the CSV file line by line and then split each line using the comma as a delimiter. We'll store the values in a List Array.

// Java code for Method 1

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CSVToListMethod1 {
    public static void main(String[] args) {
        String csvFile = "data.csv"; // Replace with your CSV file path
        List<String[]> data = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] values = line.split(",");
                data.add(values);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Display the output
        for (String[] row : data) {
            for (String value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

In this method, we open a BufferedReader to read the CSV file (data.csv). We then loop through each line using readLine() and split the line into an array of strings using the split(",") method, where the comma acts as the delimiter. We add each array of values to the data List. Finally, we display the contents of the data List, which represents the CSV data in List Array format.

Output:

Assuming the CSV file (data.csv) contains the following data:

Name,Age,Location
John,30,New York
Emily,25,Los Angeles
Michael,35,Chicago

The output of Method 1 will be:

Name Age Location 
John 30 New York 
Emily 25 Los Angeles 
Michael 35 Chicago 

Method 2: Using Apache Commons CSV

In this method, we will leverage the Apache Commons CSV library to handle CSV parsing in a more robust and flexible way. The library provides easy-to-use classes that simplify CSV parsing tasks.

// Java code for Method 2

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

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CSVToListMethod2 {
    public static void main(String[] args) {
        String csvFile = "data.csv"; // Replace with your CSV file path
        List<String[]> data = new ArrayList<>();

        try (CSVParser parser = new CSVParser(new FileReader(csvFile), CSVFormat.DEFAULT)) {
            for (CSVRecord record : parser) {
                String[] values = new String[record.size()];
                for (int i = 0; i < record.size(); i++) {
                    values[i] = record.get(i);
                }
                data.add(values);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Display the output (same as Method 1)
        for (String[] row : data) {
            for (String value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

In this method, we use the Apache Commons CSV library to parse the CSV file. The CSVFormat.DEFAULT constant specifies the default CSV format, which uses a comma as the delimiter and handles quotes and escape characters properly.

We create a CSVParser with the FileReader pointing to the CSV file path. The CSVParser allows us to iterate through each record (i.e., each line) in the CSV file. We then extract each value from the record and add them to the data List.

Output:

The output of Method 2 will be the same as Method 1, assuming the same input CSV file.

Method 3: Using OpenCSV

OpenCSV is another popular library for handling CSV operations in Java. It offers a rich set of features for reading and writing CSV data.

// Java code for Method 3

import com.opencsv.CSVReader;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CSVToListMethod3 {
    public static void main(String[] args) {
        String csvFile = "data.csv"; // Replace with your CSV file path
        List<String[]> data = new ArrayList<>();

        try (CSVReader reader = new CSVReader(new FileReader(csvFile))) {
            String[] values;
            while ((values = reader.readNext()) != null) {
                data.add(values);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Display the output (same as Method 1)
        for (String[] row : data) {
            for (String value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

In this method, we use the OpenCSV library to read the CSV file. The CSVReader class simplifies the process of parsing and reading CSV data. We open the CSVReader with the FileReader pointing to the CSV file and then use the readNext() method to get each line as an array of strings. We add each array of values to the data List, just like in the previous methods.

Output:

The output of Method 3 will be the same as Method 1 and 2, assuming the same input CSV file.

Conclusion:

In this blog, we explored various methods to convert CSV data into a List Array in Java. We started with a basic approach using BufferedReader and split, then progressed to more advanced techniques using libraries like Apache Commons CSV and OpenCSV.

Comments (0)

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