遍历 Java 列表
Iterate through Java List
我正在编写 Spring MVC Web 应用程序
我有一个 List
,我使用
填充
List items = jdbcTemplate.queryForList(query);
现在,当我使用 JSTL
:
在 View
中打印它时,它看起来像这样
[{id=1, name=John, status=1}, {id=2, name=Smith, status=1}]
同样,在 JSTL
中,我可以像这样遍历它:
<c:forEach var="item" items="${items}">
${item.id}, ${item.name}, ${item.status}
</c:forEach>
我想在 Controller
中做同样的事情,以便得到 id
List list = "";
for (int i = 0; i < items.size(); i++) {
list += items.get(i) + ",";
}
但是如何从单元格中获取 ID?
问题是你这样做:
List items = jdbcTemplate.queryForList(query);
这意味着,您将列表声明为 原始 数据持有者(顺便说一句,这是一种不好的做法)
如果你改为
List<Map<String, Object>> items = jdbcTemplate.queryForList(query);
然后你可以轻松地做类似
的事情
List<Map<String, Object>> myFooList = new ArrayList<Map<String, Object>>();
for (Map<String, Object> map : myFooList) {
// your index here like foo.getId()
}
我正在编写 Spring MVC Web 应用程序
我有一个 List
,我使用
List items = jdbcTemplate.queryForList(query);
现在,当我使用 JSTL
:
View
中打印它时,它看起来像这样
[{id=1, name=John, status=1}, {id=2, name=Smith, status=1}]
同样,在 JSTL
中,我可以像这样遍历它:
<c:forEach var="item" items="${items}">
${item.id}, ${item.name}, ${item.status}
</c:forEach>
我想在 Controller
中做同样的事情,以便得到 id
List list = "";
for (int i = 0; i < items.size(); i++) {
list += items.get(i) + ",";
}
但是如何从单元格中获取 ID?
问题是你这样做:
List items = jdbcTemplate.queryForList(query);
这意味着,您将列表声明为 原始 数据持有者(顺便说一句,这是一种不好的做法)
如果你改为
List<Map<String, Object>> items = jdbcTemplate.queryForList(query);
然后你可以轻松地做类似
的事情List<Map<String, Object>> myFooList = new ArrayList<Map<String, Object>>();
for (Map<String, Object> map : myFooList) {
// your index here like foo.getId()
}