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

Java:如何过滤ArrayList获取id为1的Person对象?Collections/Stream尝试失败

Java集合过滤实现方案

问题说明

现有如下Person实体类和包含多个Person对象的ArrayList,需要过滤出id为"1"的对象,存入新的ArrayListfilterednewArraylist。

实体类代码

class Person {
    private String id;
    private String name;
    private int age;

    // 构造方法
    public Person(String id,String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    // Getter和Setter方法
    public String getID() {
        return id;
    }

    public void setID(String id) {
        this.id = id;
    }

    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 static void main(String[] args) {
    ArrayList<Person> personList = new ArrayList<>();

    personList.add(new Person("1","John", 25));
    personList.add(new Person("2","Alice", 30));
    personList.add(new Person("3","Bob", 28));
}

有效实现方案

1. 传统循环遍历方式(兼容所有Java版本)

通过遍历原集合,判断每个对象的id是否符合条件,符合则加入新集合:

public static void main(String[] args) {
    ArrayList<Person> personList = new ArrayList<>();
    personList.add(new Person("1","John", 25));
    personList.add(new Person("2","Alice", 30));
    personList.add(new Person("3","Bob", 28));

    ArrayList<Person> filterednewArraylist = new ArrayList<>();
    for (Person person : personList) {
        // 注意调用实体类中定义的getID()方法(D为大写)
        if ("1".equals(person.getID())) {
            filterednewArraylist.add(person);
        }
    }

    // 验证过滤结果
    for (Person p : filterednewArraylist) {
        System.out.println("过滤得到的对象:" + p.getName() + ",id:" + p.getID());
    }
}

2. Stream流方式(Java 8及以上版本)

利用Java 8的Stream API进行过滤,注意调用正确的getID()方法(这是很多人尝试失败的关键):

import java.util.stream.Collectors;

public static void main(String[] args) {
    ArrayList<Person> personList = new ArrayList<>();
    personList.add(new Person("1","John", 25));
    personList.add(new Person("2","Alice", 30));
    personList.add(new Person("3","Bob", 28));

    // 过滤并收集为ArrayList
    ArrayList<Person> filterednewArraylist = personList.stream()
            .filter(person -> "1".equals(person.getID()))
            .collect(Collectors.toCollection(ArrayList::new));

    // 验证过滤结果
    filterednewArraylist.forEach(p -> 
        System.out.println("过滤得到的对象:" + p.getName() + ",id:" + p.getID())
    );
}

常见失败原因说明

如果之前使用Stream过滤无结果或编译失败,大概率是因为误调用了getId()(小写d),但实体类中定义的id获取方法是getID()(大写D),导致无法正确获取id值进行判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:33:17