Java Algorithm (9): Filter Collection: Encapsulate method to implement filtering of student information in a Student class && and return a new collection && traverse the collection call

Java Algorithm (9)

Filter ArrayList generic collection

	    过滤集合:封装方法,实现对一个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;

    }
}

Output example:

Name: Li Si—Age: 13
Name: Wang Wu—Age: 15
Name: Xiao Qi—Age: 17

Supongo que te gusta

Origin blog.csdn.net/Forever_Hopeful/article/details/134554524
Recomendado
Clasificación