Java – traversal object array list
•
Java
I am using native SQL to query with the following code
private <T> List<T> executeNativeQuery(String queryString,Map<String,Object> param,Class<T> clazz) {
Query query = entityManager.createNativeQuery(queryString);
if (param != null && param.size() > 0) {
for (Map.Entry<String,Object> entry : param.entrySet()) {
query.setParameter(entry.getKey(),entry.getValue());
}
}
List<T> resultList = query.getResultList();
return resultList;
}
The following database results are obtained
VendorName | IncidentID | IncidentStatus | IncidentDate ------------------------------------------------------- XYZ | 100 | Open | 02-JUN-2011 ABC | 101 | Closed | 03-JUN-2011 MNP | 102 | Open | 01-JUN-2011 LPQ | 103 | Open | 01-APR-2011
To iterate this result, I am using the following method
Iterator iter=resultList.iterator();
while (iter.hasNext()) {
Object[] result= (Object[]) iter.next();
System.out.println("Vendor Name-->" +result[0]);
}
Is there a better way to traverse the list?
Solution
A "better method" (Java 5 for each) will actually use iterators to convert to what you display, but the syntax is better:
for (Object[] result : resultList) {
// ...
Another "better way" relies on the fact that you know the size of the list, and you can use counters in the for loop:
for (int i = 0; i < resultList.size(); i++) {
Object[] result = resultList.get(i);
// ... the rest ...
In a word, there are several ways to iterate the list, but there are "better" ways: it's a use case problem (if you're using it, I can fight back against other things, or you use iterators to remove some elements from the list) or just taste (low-level and syntax sugar)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
