Here's a Java implementation of a CSV file analyzer, mimicking the functionality of the Python script you previously requested. This version uses the OpenCSV library for reading CSV files and performs basic data analysis tasks such as:
- Reading the CSV file
- Displaying the first few rows
- Providing metadata (number of rows, columns)
- Calculating summary statistics for numerical columns
- Checking for missing values
✅ Prerequisites
Before running the code, make sure to include the OpenCSV dependency. If you're using Maven, add this to your pom.xml:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.7.1</version>
</dependency>
🧠 Java Code: CSV Data Analyzer
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class CSVAnalyzer {
public static void main(String[] args) {
String filePath = "your_file.csv"; // Update with your actual file path
try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
List<String[]> data = reader.readAll();
if (data.isEmpty()) {
System.out.println("❌ File is empty.");
return;
}
String[] headers = data.get(0);
List<String[]> rows = data.subList(1, data.size());
System.out.println("✅ File loaded successfully!");
System.out.println("📊 Dataset Preview (first 5 rows):");
printRows(headers, rows.subList(0, Math.min(5, rows.size())));
System.out.println("\n🧾 Dataset Summary:");
System.out.println("Total Rows: " + rows.size());
System.out.println("Total Columns: " + headers.length);
System.out.println("\n🧮 Summary Statistics for Numerical Columns:");
analyzeNumericalColumns(headers, rows);
System.out.println("\n⚠️ Missing Values Check:");
checkMissingValues(headers, rows);
} catch (IOException e) {
System.err.println("❌ Error reading file: " + e.getMessage());
} catch (CsvValidationException e) {
System.err.println("❌ CSV validation error: " + e.getMessage());
}
}
private static void printRows(String[] headers, List<String[]> rows) {
System.out.println(String.join(", ", headers));
for (String[] row : rows) {
System.out.println(String.join(", ", row));
}
}
private static void analyzeNumericalColumns(String[] headers, List<String[]> rows) {
Map<String, List<Double>> numericalData = new HashMap<>();
for (int i = 0; i < headers.length; i++) {
String header = headers[i];
List<Double> columnData = new ArrayList<>();
for (String[] row : rows) {
String value = row[i].trim();
if (!value.isEmpty()) {
try {
columnData.add(Double.parseDouble(value));
} catch (NumberFormatException e) {
// Skip non-numeric values
}
}
}
if (!columnData.isEmpty()) {
numericalData.put(header, columnData);
}
}
for (Map.Entry<String, List<Double>> entry : numericalData.entrySet()) {
String colName = entry.getKey();
List<Double> values = entry.getValue();
double sum = values.stream().mapToDouble(Double::doubleValue).sum();
double mean = sum / values.size();
double min = Collections.min(values);
double max = Collections.max(values);
System.out.printf("Column: %s%n", colName);
System.out.printf(" Count: %d%n", values.size());
System.out.printf(" Min: %.2f%n", min);
System.out.printf(" Max: %.2f%n", max);
System.out.printf(" Mean: %.2f%n%n", mean);
}
}
private static void checkMissingValues(String[] headers, List<String[]> rows) {
for (int i = 0; i < headers.length; i++) {
String header = headers[i];
int missingCount = 0;
for (String[] row : rows) {
if (row[i].trim().isEmpty()) {
missingCount++;
}
}
if (missingCount > 0) {
System.out.printf("Column '%s' has %d missing values.%n", header, missingCount);
}
}
}
}