注意:所有文章除特别说明外,转载请注明出处.
Java List集合遍历的几种方式
1.for循环遍历
//在这里新建一个List集合
List<Teacher> teacherLists = new ArrayList<Teacher>();
//然后遍历集合
for (int i = 0; i < teacherList.size(); i++){
Teacher teacher = teacherList.get(i);
if (teacher != null){
teacherLists.add(teacher);
}
model.addAttribute("teacherList",teacherLists);
}
2.for循环(迭代器)
for (Iterator iterators = teacherList.iterator();iterators.hasNext();){
Teacher teacher = (Teacher) iterators.next();
String tname = teacher.getName();
model.addAttribute("teacherList",tname);
}
3.for循环(数组)
for (int i=0; i < teacherList.size(); i++){
String[] arr = new String[teacherList.size()];
for (int j = 0; j < teacherList.size(); j++){
arr[i] = teacherList.get(j).getName();
model.addAttribute("teacherList",arr[i]);
}
//model.addAttribute("teacherList",teacherList.get(i));
}
//model.addAttribute("teacherList",teacherList);
4.F-E
在前端输出的时候,如果输出的是List集合,那么输出之后,还需要转换成具体的输出,比如:teacherList.getName(),teacherList.getOffice等。然后在之前加上<#list>标签能遍历所有的元素。
<#list teacherList as teacher>
<tr>
<td>${teacher.getStaffno()}</td>
<td>${teacher.getName()}</td>
<td>${teacher.getOffice()}</td>
</tr>
</#list>