定义一个方法,方法接受一个集合对象(泛型为Student)
方法内部将年龄低于18的学生对象找出
并存入新合集,方法返回新集合
package ArrayTest;
import java.util.ArrayList;
public class ArrayListTest3 {
/**
* 需求: 定义一个方法,方法接受一个集合对象(泛型为Student)
* 方法内部将年龄低于18的学生对象找出
* 并存入新合集,方法返回新集合
*/
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
/**
*
Student stu1 = new Student("张三",23);
Student stu2 = new Student("李四",14);
Student stu3 = new Student("王五",15);
*/
list.add(new Student("张三", 23));
list.add(new Student("李四", 14));
list.add(new Student("王五", 15));
ArrayList<Student> newList = filter(list);
//遍历新集合,调用Student类的get方法打印数据
for (int i = 0; i < newList.size(); i++) {
Student s = newList.get(i);
System.out.println(s.getName() + "---" + s.getAge());
}
}
private static ArrayList<Student> filter(ArrayList<Student> list) {
//创建新集合,准备存放筛选后的学生对象
ArrayList<Student> newList = new ArrayList<>();
//遍历集合中的每一个学生对象
for (int i = 0; i < list.size(); i++) {
Student stu = list.get(i);
if (stu.getAge() < 18) {
//把符合条件的对象添加到新集合
newList.add(stu);
}
}
return newList;
}
}