We told you about the new Posts A-to-Z feature on NixMash Spring in the previous post where we detailed construction of the Alphabetical Navigation Links. We'll finish our 2-part look at Posts A-to-Z on the topic of generating grouped output with Spring and Thymeleaf.
What we're essentially doing is customizing our PostRepository.FindAll() Post list by converting it to simple PostDTO objects containing the Post Title, the Name (i.e., title slug for the url) and a new alphaKey field which syncs with the Alphabet Navigation Link anchor tags and is the key to our grouping logic.
Below is the Post Service getAlphaPosts() method where we perform a 2-step sorting and grouping, assigning each record an alphaKey based on the Post Title first letter and if it is alphabetic or numeric. Nice and clean with Java 8 Streams.
We use an efficient .map() approach to converting the Post object to a PostDTO object with title, name and alphaKey fields populated. Let's look at those mapping methods.
The secret of grouping data is packaging it with just those fields the UI processing tool (in our case, Thymeleaf) needs to iterate over it and respond accordingly to changes. It must also be sorted before sent to the client in exactly the way you want it to appear. Let's look at how Thymeleaf performs the final work in grouping our PostDTO list.
We iterate over the alphaLink items (“09″,”A”,”B”…) and if the item contains posts we create the HTML Anchor tag and display the posts which contain that alphaKey. Because our post list was sorted and prepped on the server, the client logic can concentrate on displaying each record rather than manipulating it.
Several tests accompany the grouped posts list, but here's an interesting @Test where we're confirming that Post Titles which begin with any numeric value contain the “09” alphaKey.
Our H2 test data contains 3 post titles which begin with digits. We iterate over the grouped posts knowing our .findFirst() will retrieve a post title starting with “1” on the first loop, and a post title starting with “2” on the second. We confirm the postDTO is present and that its alphaKey is “09” regardless of first digit.