How to Build an SQL‑Style Console Table Utility in Java
The article presents a Java ConsoleTable class that formats Map and List data into a tidy, SQL‑client‑like grid for console output, explains its implementation details, shows usage examples, and discusses the use of Java Stream APIs.
When testing, the author needed a tidy console output similar to an SQL client, so they created a simple ConsoleTable utility in Java that formats Map and List data into a grid.
Usage: call ConsoleTable.show(map) or ConsoleTable.show(listOfRows). Header support is not yet implemented.
Example code demonstrates creating sample Lists and a Map, then calling show to display them, followed by an image of the output.
The class ConsoleTable extends a base SourceCode and maintains a rowLength list to store column widths. For Map output, it determines the maximum key length and value length, adds padding, builds a header line, iterates over entries, formats each cell with getCel, and outputs the assembled string.
For List output, it first scans all rows to compute the maximum width of each column, adds two spaces of padding, then builds the header line, iterates over rows and columns, filling missing cells with an empty placeholder, formats each cell, and outputs the result.
The helper method getCel(int column, String content) retrieves the column width, calculates left and right padding, and returns the cell string surrounded by vertical bars. getHeader() creates the top and bottom border by joining repeated "-" strings for each column width, surrounded by "+".
The implementation relies heavily on Java 8 Stream APIs, such as map.keySet().stream().mapToInt(...).max() and rowLength.stream().map(...).collect(Collectors.toList()), which the author notes improves coding efficiency despite some unfamiliarity. They also mention that using Java Streams in Groovy can cause compatibility issues, so sticking to native Java syntax is preferable.
Future work includes adding header support, handling additional data types, and side‑bar features.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
