How can I optimize the code reducing the similar repetitive parameters

159 Views Asked by At

I want to optimize this code instead of using td(String.valueof(dataset.get())) mutliple times. I am relatively new to lambda expressions usage and not able to figure out a better way than this

Code need to be optimized

  return table(thead(tr(each(columnHeaders, header -> 
  th(String.valueOf(header))))),
  tbody(each(myList, dataset ->
  tr(td(String.valueOf(dataset.get(0))), 
  td(String.valueOf(dataset.get(1))), 
  td(String.valueOf(dataset.get(2))), 
  td(String.valueOf(dataset.get(3))), 
  td(String.valueOf(dataset.get(4))),
  td(String.valueOf(dataset.get(5))), 
  td(String.valueOf(dataset.get(6))), 
  td(String.valueOf(dataset.get(7))), 
  td(String.valueOf(dataset.get(8))), 
  td(String.valueOf(dataset.get(9))),
  td(String.valueOf(dataset.get(10)))

      ))
  )
)
2

There are 2 best solutions below

0
On BEST ANSWER

I see, you're using j2html.

I think you can do this in one line like this:

return table(thead(tr(each(columnHeaders, header -> th(String.valueOf( tbody(each(myList, dataset -> each(dataset, data -> td(data)))))

But it probably reads better if you break it out a little bit:

return table(thead(tr(each(columnHeaders, 
                           header -> th(String.valueOf(header))))),
             tbody(each(myList, 
                        dataset -> each(dataset, data -> td(String.valueOf(data))))));

All that I've done here, is inside your call to tbody you say each(myList..., then just do each again for every element of myList.

If you made sure that columnHeaders and myList were typed collections (like List<String>) then you could do something like this:

return table(thead(tr(each(columnHeaders, TagCreator::header))),
             tbody(each(myList, 
                        dataset -> each(dataset, TagCreator::td))));
1
On

Don't know what library you're using so have made an assumption for tr() and td() return types:

private TR trOf(List<?> dataset, int startIdx, int endIdxInclusive) {
    List<TD> tds = IntStream.rangeClosed(startIdx, endIdxInclusive).map(i -> tdOf(dataset, i)).collect(Collectors.toList());

    return tr(tds.toArray(new TD[0]));
}

private TD tdOf(List<?> dataset, int idx) {
    return td(String.valueOf(dataset.get(idx));
}

Then:

return table(thead(tr(each(columnHeaders, header -> 
th(String.valueOf(header))))),
tbody(each(myList, dataset ->
trOf(dataSet,0,10)

    ))
)