Java算法(九):过滤集合:封装方法,实现对一个Student类中的学生信息的筛选 && 并且返回一个新的集合 && 遍历集合调用

Java算法(九)

过滤ArrayList泛型集合

	    过滤集合:封装方法,实现对一个Student类中的学生信息的筛选 && 并且返回一个新的集合 && 遍历集合调用
package com.liujintao.test;

import com.liujintao.domain.Student;

import java.util.ArrayList;


public class ArrayListTest05 {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("张三", 23));
        list.add(new Student("李四", 13));
        list.add(new Student("王五", 15));
        list.add(new Student("赵六", 23));
        list.add(new Student("小七", 17));
        ArrayList<Student> newList = handleFilter(list);
        // 打印小于 18 岁的学生信息
        for (Student stu : newList) {
    
    
            System.out.println("姓名:" + stu.getName() + "---年龄:" + stu.getAge());
        }
    }

    public static ArrayList<Student> handleFilter(ArrayList<Student> list) {
    
    
        // 这个集合存放符合条件的数据
        ArrayList<Student> eligibleList = new ArrayList<>();
        // 遍历判断
        for (Student stu : list) {
    
    
            if (stu.getAge() < 18) {
    
    
                // 将符合条件的对象存入到新地集合中
                eligibleList.add(stu);
            }
        }
        // 将新的数据暴露出去
        return eligibleList;

    }
}

输出示例:

姓名:李四—年龄:13
姓名:王五—年龄:15
姓名:小七—年龄:17

猜你喜欢

转载自blog.csdn.net/Forever_Hopeful/article/details/134554524