Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Pulling a list of vendors and displaying them into columns JSP Functions

K Jack
Greenhorn
Posts: 2
I am getting a list of names and I would like to display them into (3) columns. Whats would be the best way to do this using a jsp function?

List:

apples
oranges
cherries
limes
pineapples
grapefruits
coconuts
watermelons
grapes
bananas
pears
peaches
Expected Output -

Column 1 - apples, oranges, cherries, and limes /
Column 2 - pineapples, grapefruits, coconuts, and watermelons /
Column 3 - grapes, bananas, pears, peaches

1. Lets say that I wanted to specify how many rows are in each column, what would be the best way to do this using a jsp function?

2. Another scenario would be, if there is a list of 13 items and you divide that by the number of columns (3), you would get 4.333333333..

What function example could I used to get 6 in the first column, 6 in the second column and 1 in the 3rd column?

Any thoughts or comments I would really be grateful for the help...

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65278
95
Sounds like just a little bit of math to me. The JSTL <c:forEach> tag can loop through the list, or even a number of steps (determined by dividing the list length by 3, for example).

To start, I'd figure out what the expected HTML should be, and then, write JSP to emit that HTML.

Stefan Evans
Bartender
Posts: 1787
10
The tricky bit is the ordering.
Printing out an HTML table, you normally specify a row at a time, rather than data for each column.

You want to do the transpose of that - all of column 1, then column2, then column3

To make the generation of the HTML easier, I would transform your list into a datastructure that mimics the layout of that table, and then print from that
- It could be a 2 dimensional table with some entries being blank
- It could be a List of rows then columns with null placeholders for a blank column.

You might find the subList function in List useful.

Here is some simple stupid java code that does something along those lines.
It takes the originally sorted list, and fiddles it into a list that can then be iterated over to produce your table (assuming new row after every 3 columns)
It is by no means perfect and not flexible at all, but may give you a couple of ideas.