Java List过滤 Stream API filter() 应用

Java 8 前用 for-each 循环或 Iterator 处理集合,引入 Stream API 后可更简洁、声明式地处理集合,在复杂数据处理时更便捷

1. Stream与Filter基础

Stream 是从支持数据源获取数据的序列,有强大 API 可执行中间和最终操作,能内部并行化提升大规模数据处理性能,基于函数式编程逻辑清晰,可利用并行计算提升大数据处理速度,惰性求值避免一次性加载整个集合

filter 是 Stream 的中间操作,接受谓词函数参数,返回新 Stream,包含满足条件元素,如以下代码展示如何用 filter 从 words 列表中筛选以"c"开头的单词。

java 复制代码
List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
List<String> filteredWords = words.stream()
                                 .filter(word -> word.startsWith("c"))
                                 .collect(Collectors.toList());

2. 多条件筛选

Stream API 可链式调用多个 filter 等中间操作实现多条件筛选,此示例展示了根据年龄和性别条件过滤 30 岁以下女性对象。

java 复制代码
List<Person> people = ... // 假设Person类有age和gender属性
List<Person> youngFemales = people.stream()
                                .filter(p -> p.getAge() < 30)
                                .filter(p -> "female".equals(p.getGender()))
                                .collect(Collectors.toList());

3. 实战示例

假设我们有个Employee类,有name(姓名)、age(年龄)、salary(薪水)属性,有个员工列表,要筛选出年龄大于 30 岁且薪水超 50000 的员工。先定义Employee

java 复制代码
public class Employee {
    private String name;
    private int age;
    private double salary;

    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

然后创建员工列表,用 Stream API 过滤数据

java 复制代码
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFilterExample {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
                new Employee("Alice", 32, 60000),
                new Employee("Bob", 28, 55000),
                new Employee("Charlie", 35, 70000),
                new Employee("David", 26, 45000),
                new Employee("Eve", 30, 55000)
        );

        // 使用Stream API过滤数据
        List<Employee> filteredEmployees = employees.stream()
                                                  .filter(employee -> employee.getAge() > 30)
                                                  .filter(employee -> employee.getSalary() > 50000)
                                                  .collect(Collectors.toList());

        // 输出结果
        System.out.println("Filtered Employees: ");
        filteredEmployees.forEach(System.out::println);
    }
}

在代码中,先调用employees.stream()将列表转为 Stream,经两次链式调用.filter()按年龄和薪水条件筛选,再用.collect(Collectors.toList())将满足条件的员工对象收集到新列表,运行后输出年龄大于 30 岁且薪水超过 50000 的员工信息

4. 应用场景总结

  • 数据清洗:筛选符合条件的数据。
  • 报表统计:快速汇总特定条件统计数据。
  • 业务逻辑处理:简化复杂业务场景循环和判断。
  • 数据库查询结果处理:对接查询结果后过滤转换数据。

What is Java technology and why do I need it?

Java is a programming language and computing platform first released by Sun Microsystems in 1995. It has evolved from humble beginnings to power a large share of today's digital world, by providing the reliable platform upon which many services and applications are built. New, innovative products and digital services designed for the future continue to rely on Java, as well.

While most modern Java applications combine the Java runtime and application together, there are still many applications and even some websites that will not function unless you have a desktop Java installed. Java.com, this website, is intended for consumers who may still require Java for their desktop applications -- specifically applications targeting Java 8. Developers as well as users that would like to learn Java programming should visit the dev.java website instead and business users should visit oracle.com/java for more information.

Is Java free to download?

Yes, Java is free to download for personal use.

Java is also free for development: developers can find all the development kits and other useful tools at https://www.oracle.com/javadownload/.

Why should I upgrade to the latest Java patch each quarter when prompted?

The latest Java patches contain important enhancements to improve performance, stability and security of the Java applications that run on your machine. Installing these updates will ensure that your Java applications continue to run with the most up-to-date version.

相关推荐
霜绛15 分钟前
C#知识补充(一)——ref和out、成员属性、万物之父和装箱拆箱、抽象类和抽象方法、接口
开发语言·笔记·学习·c#
T.Ree.24 分钟前
cpp_list
开发语言·数据结构·c++·list
laocooon52385788627 分钟前
C++ 图片加背景音乐的处理
开发语言·c++
爱编程的鱼36 分钟前
C# var 关键字详解:从入门到精通
开发语言·c#·solr
MATLAB代码顾问39 分钟前
MATLAB实现TCN神经网络数值预测
开发语言·matlab
2301_796512521 小时前
Rust编程学习 - 如何利用代数类型系统做错误处理的另外一大好处是可组合性(composability)
java·学习·rust
南汐汐月1 小时前
重生归来,我要成功 Python 高手--day33 决策树
开发语言·python·决策树
清水1 小时前
Spring Boot企业级开发入门
java·spring boot·后端
一个不称职的程序猿2 小时前
高并发场景下的缓存利器
java·缓存
星释2 小时前
Rust 练习册 :Proverb与字符串处理
开发语言·后端·rust