You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据匹配年龄列表过滤Java中的Person对象列表?

解决方案

你需要修改两个核心点来实现需求:

  1. 给Person类添加age属性的getter方法(因为age是私有属性,外部无法直接访问)
  2. 在Stream的filter逻辑中,用ages.contains()判断当前Person的年龄是否在目标列表内

修改后的完整代码

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {

        Person p1 = new Person("John", 25);
        Person p2 = new Person("Lisa", 54);
        Person p3 = new Person("Mike", 61);
        List<Person> people = new ArrayList<>();
        people.add(p1);
        people.add(p2);
        people.add(p3);

        List<Integer> ages = Arrays.asList(25, 54);
        List<Person> specificAges = people.stream()
                .filter(p -> ages.contains(p.getAge()))
                .collect(Collectors.toList());

        System.out.println(specificAges);
    }
}

class Person {
    private String firstName;
    private Integer age;

    public Person(String firstName, Integer age) {
        this.firstName = firstName;
        this.age = age;
    }

    // 添加age的getter方法,用于外部访问私有属性
    public Integer getAge() {
        return age;
    }

    @Override
    public String toString() {
        return firstName + " " + age;
    }
}

关键细节说明

  • 必须添加getAge():私有成员变量无法被外部类直接访问,所以需要通过getter方法获取年龄值。
  • 使用ages.contains(p.getAge()):这个方法会安全检查当前Person的年龄是否存在于目标列表中,相比直接用==更可靠(避免Integer对象在缓存范围外时的相等性判断异常)。
  • 不能省略collect(Collectors.toList()):Stream是惰性求值,必须通过collect方法将流转换为List集合,才能得到最终的过滤结果。

运行代码后,输出结果与预期一致:[John 25, Lisa 54]

内容的提问来源于stack exchange,提问作者Sherbet Head

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 21:00:05