Here's a Java solution to analyze CSV data using Apache Commons CSV and Apache Commons Math libraries. This script provides summary statistics, data quality checks, and generates visualizations using JFreeChart:
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.statistics.HistogramDataset;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
public class CsvAnalyzer {
private static final int HISTOGRAM_BINS = 15;
private static final int TOP_CATEGORIES = 10;
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java CsvAnalyzer <csv-file-path>");
System.exit(1);
}
String filePath = args[0];
analyzeCsv(filePath);
}
private static void analyzeCsv(String filePath) {
try {
// Read file metadata
File file = new File(filePath);
long fileSize = file.length() / 1024; // KB
String fileName = file.getName();
// Parse CSV content
CSVParser parser = CSVParser.parse(file, StandardCharsets.UTF_8, CSVFormat.DEFAULT.withFirstRecordAsHeader());
List<String> headers = parser.getHeaderNames();
List<CSVRecord> records = parser.getRecords();
int rowCount = records.size();
int colCount = headers.size();
System.out.println("📊 Analyzing: " + fileName + " (" + fileSize + " KB)");
System.out.println("📂 Columns: " + colCount + ", Rows: " + rowCount);
// Data storage
Map<String, List<String>> columns = new HashMap<>();
Map<String, DescriptiveStatistics> numericStats = new HashMap<>();
Map<String, Map<String, Integer>> categoricalCounts = new HashMap<>();
Set<String> numericColumns = new HashSet<>();
Set<String> categoricalColumns = new HashSet<>();
// Initialize data structures
for (String header : headers) {
columns.put(header, new ArrayList<>());
categoricalCounts.put(header, new HashMap<>());
}
// Collect data and detect types
for (CSVRecord record : records) {
for (String header : headers) {
String value = record.get(header);
columns.get(header).add(value);
// Try parsing as number
try {
Double.parseDouble(value);
numericColumns.add(header);
} catch (NumberFormatException e) {
categoricalColumns.add(header);
}
}
}
// Remove columns that had mixed types
numericColumns.removeAll(categoricalColumns);
categoricalColumns.removeAll(numericColumns);
// Calculate statistics
for (String header : headers) {
if (numericColumns.contains(header)) {
DescriptiveStatistics stats = new DescriptiveStatistics();
for (String value : columns.get(header)) {
if (!value.isEmpty()) {
stats.addValue(Double.parseDouble(value));
}
}
numericStats.put(header, stats);
} else {
Map<String, Integer> counts = categoricalCounts.get(header);
for (String value : columns.get(header)) {
counts.put(value, counts.getOrDefault(value, 0) + 1);
}
}
}
// Print data sample
System.out.println("\n🔍 First 3 rows:");
for (int i = 0; i < Math.min(3, records.size()); i++) {
System.out.println(records.get(i));
}
// Print data types and missing values
System.out.println("\n🧩 Data Overview:");
System.out.printf("%-15s %-10s %-15s %-15s%n", "Column", "Type", "Missing", "% Missing");
for (String header : headers) {
long missing = columns.get(header).stream().filter(String::isEmpty).count();
double percentMissing = (double) missing / rowCount * 100;
String type = numericColumns.contains(header) ? "Numeric" : "Categorical";
System.out.printf("%-15s %-10s %-15d %.1f%%%n",
header, type, missing, percentMissing);
}
// Numeric analysis
if (!numericStats.isEmpty()) {
System.out.println("\n📈 Numeric Columns Analysis:");
System.out.printf("%-12s %10s %10s %10s %10s %10s %10s %10s%n",
"Column", "Count", "Min", "Max", "Mean", "StdDev", "25th", "75th");
for (Map.Entry<String, DescriptiveStatistics> entry : numericStats.entrySet()) {
DescriptiveStatistics stats = entry.getValue();
System.out.printf("%-12s %10d %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f%n",
entry.getKey(),
stats.getN(),
stats.getMin(),
stats.getMax(),
stats.getMean(),
stats.getStandardDeviation(),
stats.getPercentile(25),
stats.getPercentile(75));
}
// Generate histograms
for (String col : numericColumns) {
double[] values = numericStats.get(col).getValues();
if (values.length > 0) {
saveHistogram(values, col + " Distribution", "value", "frequency",
col + "_histogram.png");
System.out.println("✅ Saved histogram: " + col + "_histogram.png");
}
}
}
// Categorical analysis
if (!categoricalColumns.isEmpty()) {
System.out.println("\n📊 Categorical Columns Analysis:");
for (String col : categoricalColumns) {
System.out.println("\n" + col + ":");
Map<String, Integer> counts = categoricalCounts.get(col);
// Sort by frequency descending
List<Map.Entry<String, Integer>> sorted = counts.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(TOP_CATEGORIES)
.collect(Collectors.toList());
// Print top categories
for (Map.Entry<String, Integer> entry : sorted) {
System.out.printf(" %-20s: %d%n", entry.getKey(), entry.getValue());
}
// Generate bar chart
saveBarChart(sorted, col + " Top Categories", "Category", "Count",
col + "_barchart.png");
System.out.println("✅ Saved bar chart: " + col + "_barchart.png");
}
}
System.out.println("\n✔️ Analysis complete!");
parser.close();
} catch (IOException e) {
System.err.println("❌ Error analyzing CSV: " + e.getMessage());
e.printStackTrace();
}
}
private static void saveHistogram(double[] data, String title,
String xLabel, String yLabel,
String filename) throws IOException {
HistogramDataset dataset = new HistogramDataset();
dataset.addSeries("Data", data, HISTOGRAM_BINS);
JFreeChart histogram = ChartFactory.createHistogram(
title, xLabel, yLabel, dataset, PlotOrientation.VERTICAL,
true, true, false);
ChartUtils.saveChartAsPNG(new File(filename), histogram, 800, 600);
}
private static void saveBarChart(List<Map.Entry<String, Integer>> data,
String title, String xLabel, String yLabel,
String filename) throws IOException {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (Map.Entry<String, Integer> entry : data) {
dataset.addValue(entry.getValue(), "Count", entry.getKey());
}
JFreeChart barChart = ChartFactory.createBarChart(
title, xLabel, yLabel, dataset,
PlotOrientation.VERTICAL, true, true, false);
ChartUtils.saveChartAsPNG(new File(filename), barChart, 800, 600);
}
}