-1

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)))

      ))
  )
)
4

2 回答 2

2

我明白了,您使用的是 j2html。

我认为您可以像这样在一行中做到这一点:

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

但如果你把它拆开一点,它可能会读起来更好:

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

我在这里所做的一切,都是在你打电话给tbody你的时候说each(myList...的,然后each对 的每个元素再做一次myList

如果您确定columnHeadersmyList输入了集合(如List<String>),那么您可以执行以下操作:

return table(thead(tr(each(columnHeaders, TagCreator::header))),
             tbody(each(myList, 
                        dataset -> each(dataset, TagCreator::td))));
于 2019-03-22T20:01:59.937 回答
0

不知道您使用的是什么库,所以对返回类型做了一个tr()假设td()

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));
}

然后:

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

    ))
)
于 2019-03-22T19:29:49.167 回答