Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Created February 20, 2014 23:27
Show Gist options
  • Select an option

  • Save rayjcwu/9125523 to your computer and use it in GitHub Desktop.

Select an option

Save rayjcwu/9125523 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
public class TreeHierarchyPrint {
public static void main(String[] argv) {
TreeHierarchyPrint orderBy = new TreeHierarchyPrint();
orderBy.print(
new String[][] {
{ "Name", "Size", "Color", "Grade" },
{ "CCC", "Big", "Blue", "A" },
{ "DDD", "Big", "Red", "A" },
// { "EEE", "Small", "Blue", "F" },
{ "FFF", "Big", "Blue", "G"}},
new String[] { "Color", "Size", "Name" });
}
public void print(String[][] table, String[] orderBy) {
if (table.length < 2) {
return;
}
final int M = table.length;
final int N = orderBy.length;
final HashMap<String, Integer> strColMap = new HashMap<String, Integer>();
for (int i = 0; i < N; i++) {
strColMap.put(table[0][i], i);
}
// build array of Row
Row[] rows = new Row[M - 1];
for (int i = 0; i < M - 1; i++) {
rows[i] = new Row(N); // each Row contains only Column specified in orderBy
for (int j = 0; j < N; j++) {
rows[i].values[j] = table[i + 1][strColMap.get(orderBy[j])];
}
}
// sort based on orderBy
Arrays.sort(rows, new Comparator<Row>() {
@Override
public int compare(Row a, Row b) {
for (int i = 0; i < N; i++) {
if (!a.values[i].equals(b.values[i])) {
return a.values[i].compareTo(b.values[i]);
}
}
return 0; // should not be here
}
});
// print
String[] prev = new String[N];
boolean newRow = true;
for (Row row: rows) {
if (!row.values[0].equals(prev[0])) {
newRow = true;
}
for (int coli = 0; coli < N; coli++) {
String cell = row.values[coli];
if (!newRow && cell.equals(prev[coli])) {
continue;
}
printCell(row, coli);
}
prev = row.values;
newRow = false;
}
}
public void printCell(Row row, int coli) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < coli; i++) {
sb.append(" ");
}
sb.append(row.values[coli]);
System.out.println(sb.toString());
}
}
class Row {
String[] values;
public Row(int columns) {
values = new String[columns];
}
@Override
public String toString() {
return Arrays.toString(values);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment