MST

星途 面试题库

面试题:Java中如何使用流式API对集合框架中的对象进行特定属性过滤并求和

假设有一个包含员工信息的Java集合,员工类(Employee)有属性id(整数)、name(字符串)和salary(浮点数)。请使用Java流式API对集合进行操作,过滤出工资大于5000的员工,并计算这些员工的工资总和,给出代码实现。
21.2万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.util.ArrayList;
import java.util.List;

class Employee {
    private int id;
    private String name;
    private float salary;

    public Employee(int id, String name, float salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    public float getSalary() {
        return salary;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1, "Alice", 6000f));
        employees.add(new Employee(2, "Bob", 4000f));
        employees.add(new Employee(3, "Charlie", 7000f));

        float totalSalary = employees.stream()
               .filter(employee -> employee.getSalary() > 5000)
               .mapToFloat(Employee::getSalary)
               .sum();

        System.out.println("工资总和: " + totalSalary);
    }
}