Home  >  Article  >  Java  >  What are the methods for traversing List collection in java?

What are the methods for traversing List collection in java?

王林
王林forward
2020-11-13 15:58:043628browse

What are the methods for traversing List collection in java?

This article shares four traversal methods in the ordered collection List. I hope it will be helpful to everyone.

(Learning video sharing: java course)

First create a Student class to create objects and provide parameterized and parameterless constructors.

package lesson1;

public class Student {
	String name;
	int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	

}

The following are four types of traversal

package lesson1;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListTest {

	public static void main(String[] args) {
		//使用学生类创建四个对象,并给对象中的属性赋初值
		Student s1 = new Student("zhangsan1",20);
		Student s2 = new Student("zhangsan2",21);
		Student s3 = new Student("zhangsan3",22);
		Student s4 = new Student("zhangsan4",23);
		//创建一个集合
		List studentList = new ArrayList();
		
		//将上面的四个学生对象添加到集合中
		studentList.add(s1);
		studentList.add(s2);
		studentList.add(s3);
		studentList.add(s4);
		
		// 普通for循环遍历
//		for (int i = 0 ; i < studentList.size() ; i++) {
//			Student s = (Student)studentList.get(i);
//			System.out.println(s.getName());
//			System.out.println(s.getAge());
//		}
		
		//增强for循环遍历
		for (Object os:studentList) {
			Student s = (Student)os;
			System.out.println(s.getName());
			System.out.println(s.getAge());
		}
		
		//迭代器遍历
//		Iterator it = studentList.iterator();
//		while (it.hasNext()) {
//			Student s = (Student)it.next();
//			System.out.println(s.getName());
//			System.out.println(s.getAge());
//		}
		
		//jdk 1.8版本提供的forEach()方法遍历,这种方法了解就行
//		studentList.forEach((os)->{
//			Student s = (Student)os;
//			System.out.println(s.getName());
//			System.out.println(s.getAge());
//		});
		

	}

}

Related recommendations:Getting started with java

The above is the detailed content of What are the methods for traversing List collection in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete