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.

相关推荐
lly20240614 小时前
PostgreSQL 表达式
开发语言
LXMXHJ14 小时前
php开发
开发语言·php
望获linux14 小时前
【实时Linux实战系列】Linux 内核的实时组调度(Real-Time Group Scheduling)
java·linux·服务器·前端·数据库·人工智能·深度学习
Never_Satisfied14 小时前
在 JavaScript 中,删除数组中内容为xxx的元素
java·前端·javascript
MC丶科15 小时前
【SpringBoot常见报错与解决方案】端口被占用?Spring Boot 修改端口号的 3 种方法,第 3 种 90% 的人不知道!
java·linux·spring boot
怪兽201415 小时前
Redis常见性能问题和解决方案
java·数据库·redis·面试
zz-zjx15 小时前
JVM 内存结构与 GC 机制详解( 实战优化版)
java·jvm·tomcat
mjhcsp15 小时前
MATLAB 疑难问题诊疗:从常见报错到深度优化的全流程指南
开发语言·matlab
Lynnxiaowen15 小时前
今天我们开始学习python语句和模块
linux·运维·开发语言·python·学习
nvvas15 小时前
Android Studio JAVA开发按钮跳转功能
android·java·android studio