Skip to content

CSV Diff — Java source

Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.

This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.

// csv-diff — key-based row diff of two RFC-4180 CSVs. Java port (canonical
// TS: src/lib/csv-diff.ts; Go twin: cli/csv-diff). Mirrors the sibling
// ports: an RFC-4180 parser (quoted cells with embedded commas, quotes and
// newlines; CR dropped; a trailing field without a newline still completes
// its row) with blank single-cell rows dropped as trailing noise, strict
// per-side validation (empty CSV, duplicate columns, ragged rows, duplicate
// keys — the pinned error strings, carried as strings, never exceptions out
// of the entry point), then a key-based diff over the sorted key union:
// added/removed rows and changed rows whose differing column names come out
// sorted.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

// Package-private: display snippets keep the repo filename (csv-diff.java),
// which need not match the class name.
final class CsvDiff {
    /** One row of the diff result; before/after hold the full records. */
    static final class RowDiff {
        final String key; final String type; // "added" | "removed" | "changed"
        final List<String> columns; final Map<String, String> before, after;
        RowDiff(String key, String type, List<String> columns, Map<String, String> before, Map<String, String> after) {
            this.key = key; this.type = type; this.columns = columns; this.before = before; this.after = after;
        }
    }
    static final class DiffResult {
        final List<RowDiff> rows; final boolean same; final String error; // null mirrors TS null
        DiffResult(List<RowDiff> rows, boolean same, String error) { this.rows = rows; this.same = same; this.error = error; }
    }

    /** RFC 4180 parser mirroring the TS loop: lenient quotes, CR dropped, a
     *  trailing field without a newline still completes its row. */
    static List<List<String>> csvToRows(String csv) {
        List<List<String>> rows = new ArrayList<>();
        StringBuilder field = new StringBuilder();
        List<String> row = new ArrayList<>();
        boolean inQ = false;
        for (int i = 0; i < csv.length(); i++) {
            char ch = csv.charAt(i);
            if (inQ) {
                if (ch == '"') {
                    if (i + 1 < csv.length() && csv.charAt(i + 1) == '"') { field.append('"'); i++; }
                    else inQ = false;
                } else field.append(ch);
            } else if (ch == '"') inQ = true;
            else if (ch == ',') { row.add(field.toString()); field.setLength(0); }
            else if (ch == '\n') { row.add(field.toString()); field.setLength(0); rows.add(row); row = new ArrayList<>(); }
            else if (ch != '\r') field.append(ch);
        }
        if (field.length() > 0 || !row.isEmpty()) { row.add(field.toString()); rows.add(row); }
        return rows;
    }

    /** Blank single-cell rows are trailing noise to a diff, not data. */
    static List<List<String>> parseCsv(String text) {
        List<List<String>> out = new ArrayList<>();
        for (List<String> r : csvToRows(text))
            if (!(r.size() == 1 && r.get(0).isEmpty())) out.add(r);
        return out;
    }

    /** Strict per-side validation → [header, records]; IllegalStateException
     *  carries the pinned strings (empty CSV, duplicate column, ragged row). */
    static Object[] toRecords(List<List<String>> rows, String label) {
        if (rows.isEmpty()) throw new IllegalStateException(label + ": empty CSV");
        List<String> header = rows.get(0);
        for (int c = 0; c < header.size(); c++)
            for (int d = 0; d < c; d++)
                if (header.get(c).equals(header.get(d)))
                    throw new IllegalStateException(label + ": duplicate column \"" + header.get(c) + "\"");
        List<Map<String, String>> records = new ArrayList<>();
        for (int r = 1; r < rows.size(); r++) {
            if (rows.get(r).size() != header.size())
                throw new IllegalStateException(label + ": row " + (r + 1) + " has " + rows.get(r).size()
                    + " cells, expected " + header.size());
            Map<String, String> rec = new LinkedHashMap<>();
            for (int c = 0; c < header.size(); c++) rec.put(header.get(c), rows.get(r).get(c));
            records.add(rec);
        }
        return new Object[] { header, records };
    }

    /** Diff two CSVs by key column (default: the first header column). */
    static DiffResult csvDiff(String leftRaw, String rightRaw, String keyColumn) {
        if (leftRaw.trim().isEmpty() || rightRaw.trim().isEmpty())
            return new DiffResult(new ArrayList<>(), false, "Both inputs are required");
        try {
            Object[] l = toRecords(parseCsv(leftRaw), "Left");
            Object[] r = toRecords(parseCsv(rightRaw), "Right");
            @SuppressWarnings("unchecked") List<String> lheader = (List<String>) l[0];
            @SuppressWarnings("unchecked") List<String> rheader = (List<String>) r[0];
            @SuppressWarnings("unchecked") List<Map<String, String>> lrecs = (List<Map<String, String>>) l[1];
            @SuppressWarnings("unchecked") List<Map<String, String>> rrecs = (List<Map<String, String>>) r[1];
            String key = keyColumn != null ? keyColumn : lheader.get(0);
            if (!lheader.contains(key)) return new DiffResult(new ArrayList<>(), false, "Left: no key column \"" + key + "\"");
            if (!rheader.contains(key)) return new DiffResult(new ArrayList<>(), false, "Right: no key column \"" + key + "\"");
            if (!lheader.equals(rheader))
                return new DiffResult(new ArrayList<>(), false,
                    "Headers differ: left [" + String.join(", ", lheader) + "] vs right [" + String.join(", ", rheader) + "]");
            // LinkedHashMap keeps records by column name; duplicates are
            // detected in row order, the diff runs over the sorted key union.
            Map<String, Map<String, String>> leftBy = index(lrecs, key, "Left");
            Map<String, Map<String, String>> rightBy = index(rrecs, key, "Right");
            TreeSet<String> keys = new TreeSet<>(leftBy.keySet());
            keys.addAll(rightBy.keySet());
            List<RowDiff> rows = new ArrayList<>();
            for (String k : keys) {
                Map<String, String> lo = leftBy.get(k), ro = rightBy.get(k);
                if (lo == null) rows.add(new RowDiff(k, "added", null, null, ro));
                else if (ro == null) rows.add(new RowDiff(k, "removed", null, lo, null));
                else {
                    List<String> columns = new ArrayList<>();
                    for (String name : lheader)
                        if (!name.equals(key) && !lo.get(name).equals(ro.get(name))) columns.add(name);
                    java.util.Collections.sort(columns);
                    if (!columns.isEmpty()) rows.add(new RowDiff(k, "changed", columns, lo, ro));
                }
            }
            return new DiffResult(rows, rows.isEmpty(), null);
        } catch (IllegalStateException e) {
            return new DiffResult(new ArrayList<>(), false, e.getMessage());
        }
    }

    private static Map<String, Map<String, String>> index(List<Map<String, String>> recs, String key, String label) {
        Map<String, Map<String, String>> by = new LinkedHashMap<>();
        for (Map<String, String> rec : recs) {
            String k = rec.get(key);
            if (by.containsKey(k)) throw new IllegalStateException(label + ": duplicate key \"" + k + "\"");
            by.put(k, rec);
        }
        return by;
    }

    public static void main(String[] args) {
        DiffResult res = csvDiff("id,name\n1,Ada\n2,Bob", "id,name\n1,Ada\n2,Robert\n3,New", null);
        for (RowDiff d : res.rows) {
            System.out.println(d.key + " " + d.type
                + (d.type.equals("changed") ? " (" + d.columns + ": " + d.before + " -> " + d.after + ")" : ""));
        }
        System.out.println("same: " + res.same); // same: false
        System.out.println(csvDiff("id,name\n1,Ada\n1,Bob", "id,name\n1,Ada", null).error); // Left: duplicate key "1"
    }
}

Also available in 12 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →