gpt4 book ai didi

java - 如何在 JSTL c 中对具有重复列属性的行进行分组 :forEach

转载 作者:行者123 更新时间:2023-12-01 05:51:34 25 4
gpt4 key购买 nike

我正在使用 Java 进行编程,并且我有一个对象列表,我想在 JSTL 中进行迭代,以检查其他元素是否与当前元素有一些相似之处。我想在我的 jsp 中执行此操作,因为这只是一个显示问题。

让我们举一个虚拟的例子,假设我的对象有三个属性:id、lastname 和firstname。 id 将是一个家庭的标识符,我想在 HTML 表中显示该列表,但在迭代我的列表时,我想检查列表的其余部分以查看是否存在其他家庭成员,以便我可以将它们重新分组到一个 td 标记中.

1 | TOTO   | James 2 | FOE    | Cameron 2 | FOE    | Jessica 1 | TOTO   | Pat3 | SAMPLE | Bob

Expected result :

<table>
<tr><td>1</td><td>TOTO</td><td>James, Pat</td></tr>
<tr><td>2</td><td>FOE</td><td>Cameron, jessica</td></tr>
<tr><td>3</td><td>SAMPLE</td><td>Bob</td></tr>
</table>

同样,这是一个基本示例,您可能会想告诉我将我的家庭重新组合到模型层的其他对象中,但我不想这样做。

<小时/>

编辑: 我指的是 while 循环,因为我的列表是按 id 排序的,这样我就可以轻松检查下一个元素。但其他解决方案对我来说也不错。

最佳答案

您可以在Map中获取已处理的姓氏并对其进行拦截。

<table>
<jsp:useBean id="processed" class="java.util.HashMap" />
<c:forEach items="${persons}" var="person">
<c:if test="${empty processed[person.lastName]}">
<c:set target="${processed}" property="${person.lastName}" value="true" />
<tr>
<td>${person.familyId}</td>
<td>${person.lastName}</td>
<td>${person.firstName}
<c:forEach items="${persons}" var="other">
<c:if test="${person.lastName == other.lastName and person.firstName != other.firstName}">
, ${other.firstName}
</c:if>
</c:forEach>
</td>
</tr>
</c:if>
</c:forEach>
</table>

但是,我同意这应该在(数据)模型端完成,而不是在 View 端。

关于java - 如何在 JSTL c 中对具有重复列属性的行进行分组 :forEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4517928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com