import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class CSVApp {
final static String[][] CSV = {
{"idXX9", "1", "5", "abc"},
{"idXX10", "1", "6", "abc"},
{"idXX11", "1", "abc"},
{"idXX12", ""},
{"idXX12", "xyz","4", "5", "6"},
};
public static String [][] buildTable (final String[][] csv) {
// Alle vorkommenden Werte außer den "IDxxx?" in einem Set speichern
// zwecks Eindeutigkeit
final Set<String> columns = new LinkedHashSet<String>();
for(final String [] line : csv) {
// Position "0" ist durch "IDxxx" belegt
for(int i=1; i < line.length; i++) {
columns.add(line[i]);
}
}
// Alle vorkommenden Werte auch als Array speichern; Wird als
// vorlage für die Spalten benutzt
final String [] columnsArray = columns.toArray(new String[]{});
// Zieltabelle, +1 ist für die Kopfzeile
final String [][] table = new String[csv.length+1][columnsArray.length];
// Kopfzeile bauen, das "Spalte_..." spare ich mir. +1 für "ID"
final String tableHeader [] = new String [columns.size()+1];
tableHeader[0]="ID";
System.arraycopy(columnsArray, 0, tableHeader, 1, columnsArray.length);
table[0] = tableHeader;
// Zeilenzähler, Position 0 ist duch die Kopfzeile belegt
int offset=1;
for(final String [] row : csv) {
final String [] resultRow = new String[columnsArray.length+1];
// Hier tragen wir das "idXX???" ein
resultRow[0] = row[0];
// Die Elemente der Zeile in ein HashSet für den lookup kopieren
final Set<String> elements = new HashSet<String>();
Collections.addAll(elements, row);
// Spaltenzähler, Position 0 ist durch "IDxxx" belegt
for(int i=1; i < resultRow.length; i++) {
// Man könnte alternativ auch mit Collections.frequency() sogar die
// Häufigkeiten zählen...
resultRow[i] = (elements.contains(columnsArray[i-1]) ? "1" : "0");
}
table[offset]=resultRow;
offset++;
}
return table;
}
public static void main(String[] args) {
final String [][] table = buildTable(CSV);
final StringBuilder b = new StringBuilder();
for(final String [] row : table) {
for(final String col : row) {
b.append("\t"+col);
}
b.append("\n");
}
System.out.println(b.toString());
}
}