cdc.graphs.impl.GraphPrinter Maven / Gradle / Ivy
package cdc.graphs.impl;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import cdc.graphs.GraphAdapter;
/**
* Utility class used to print a graph as text.
*
* Mainly intended for debug purposes.
*
* @author Damien Carbonne
*/
public final class GraphPrinter {
private GraphPrinter() {
}
private static final Comparator> CLASS_COMPARATOR =
Comparator.comparing(Class::getCanonicalName);
private static void display(String title,
int total,
Iterable> items,
PrintStream out) {
final Map, Integer> counts = new HashMap<>();
for (final Object item : items) {
final Class> key = item.getClass();
counts.put(key, counts.getOrDefault(key, 0) + 1);
}
out.println(title + total);
counts.keySet()
.stream()
.sorted(CLASS_COMPARATOR)
.forEach(cls -> out.println(" " + cls.getSimpleName() + ": " + counts.get(cls)));
}
/**
* Print a graph (adapter) to an output stream.
*
* @param Node class.
* @param Edge class.
* @param adapter The graph adapter.
* @param details If true, print detailed information.
* @param out The stream to use.
*/
public static void print(GraphAdapter adapter,
boolean details,
PrintStream out) {
display("Nodes: ", adapter.getNodesCount(), adapter.getNodes(), out);
display("Edges: ", adapter.getEdgesCount(), adapter.getEdges(), out);
if (details) {
out.println("Details");
for (final N node : adapter.getNodes()) {
out.println(" " + node);
}
for (final E edge : adapter.getEdges()) {
out.println(" " + edge);
}
}
}
}