java 是否可以在jstl中使用foreach同时迭代两个项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4142631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:59:17  来源:igfitidea点击:

is it possible to iterate two items simultaneously using foreach in jstl?

javamodel-view-controllerspringjspjstl

提问by randy

I have two items from my model and I want to iterate them at the same using jstl foreach. how can I achieve this using a correct syntax?

我的模型中有两个项目,我想使用 jstl foreach 同时迭代它们。如何使用正确的语法实现这一点?

回答by dogbane

You can call varStatus.indexto get the index of the current round of iteration, and then use it as a lookup for the second list.

可以调用varStatus.index获取本轮迭代的索引,然后作为第二个列表的查找。

For example, if you have two lists people.firstnamesand people.lastnamesyou can do:

例如,如果您有两个列表people.firstnames并且people.lastnames可以执行以下操作:

<c:forEach var="p" items="${people.firstnames}" varStatus="status">
  <tr>
      <td>${p}</td>
      <td>${people.lastnames[status.index]}</td>
  </tr>
</c:forEach>

回答by Boris Pavlovi?

I assume you have to collections that you want to iterate in one go. Add a getter which will merge these two collections and use it for the iteration. For example

我假设你必须要一次性迭代的集合。添加一个 getter,它将合并这两个集合并将其用于迭代。例如

private Collection<String> first;
private Collection<String> second;

public Collection<String> getBoth()
{
  List<String> result = new ArrayList<String>();
  result.addAll(first);
  result.addAll(second);
  return result;
}

Iteration in JSTL:

JSTL 中的迭代:

<c:forEach var="p" items="${people.both}">
  <tr>
      <td>${p}</td>
  </tr>
</c:forEach>