0

I am trying to create a table that is created from Lists of different sizes. I have a list of Cars List<Car>. So in the header I want to place the names of the different companies which I did.

Then I have a List<List<CarSales>> and not all Cars exist in each carSales. So I want to iterate through the List of List of each tr (also OK) and then I want to iterate in the td though the List and place the CarSales.sales in the correct td where CarSales.mark=Car.makr of the header.

So if List<Cars> is (I mean Cars.mark)

[BMW, MERCEDES,FIAT]

And List<List<CarSales>> is (I mean object that have mark and sales inside)

[[BMW:5,FIAT:10],[MERCEDES:12]]

I want a table with:

BMW - MERCEDES - FIAT

 5  -    0     -  10

 0  -   12     -  0

1 Answer 1

1

You might be able to do that... but you can make the markup so much simpler if List<List<CarSales>> was instead a List<Map<String, Integer>> instead (where the key is the mark, and the value is the sales). Then you could have something like this:

<table>
  <tr>
    <th th:each="car: ${cars}" th:text="${car.mark}" />
  </tr>

  <tr th:each="sale: ${carSales}">
    <td th:each="car: ${cars}" th:text="${sale.get(car.mark)} ?: 0" />
  </tr>
</table>

If you want to go with your original structure, something like this might work, but it's more confusing to maintain:

<table>
  <tr>
    <th th:each="car: ${cars}" th:text="${car.mark}" />
  </tr>

  <tr th:each="sales: ${carSales}">
    <td th:each="car: ${cars}" th:with="sale=${sales.^[mark==#root.car.mark]}" th:text="${sale?.sales} ?: 0" />
  </tr>
</table>
Sign up to request clarification or add additional context in comments.

2 Comments

can you explain the th:text? what is the sale?.sale
@kyrpav in the expression sale?.sales, ?. is the safe navigation operator. It just means if sale is null then the whole expression will return null, rather than try and resolve sale.sales (which would normally throw an null pointer exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.