假设有一个对象类 Person,包含属性 name:

public class Person {
    private String name;
    
    public Person(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}

现在有一个 Person 对象的 List,我们要过滤出 name 为 '小明' 的所有数据:

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

public class Main {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person('小明'));
        personList.add(new Person('小红'));
        personList.add(new Person('小明'));
        personList.add(new Person('小李'));
        
        List<Person> filteredList = personList.stream()
                                              .filter(person -> person.getName().equals('小明'))
                                              .collect(Collectors.toList());
        
        System.out.println(filteredList);
    }
}

运行结果为:

[Person@7852e922, Person@4e25154f]

可以看到,过滤出来的结果是一个包含两个 Person 对象的 List。

Java8 使用 Stream 过滤 List 中 name 为 '小明' 的数据

原文地址: https://www.cveoy.top/t/topic/fm0i 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录