list的遍历方式
list有五种遍历方式
List<Person> personList = new ArrayList<>();
personList.add(new Person("用户1","男"));
personList.add(new Person("用户2","女"));
- 普通for循环
for(int i = 0;i<personList.size();i++){
Person p = personList.get(i);
System.out.println(p.toString());
}
- 增强型for循环
for(Person p : personList){
System.out.println(p.toString());
}
- 迭代器
Iterator<Person> iterator = personList.iterator();
while(iterator.hasNext()){
Person p = iterator.next();
System.out.println(p.toString());
}
- lamda表达式
personList.forEach(person -> {
System.out.println(person);
});
- list集合内置迭代器
ListIterator<Person> listIterator = personList.listIterator();
while(listIterator.hasNext()){
System.out.println(listIterator.next());
}
|