MST

星途 面试题库

面试题:Java中Stream filter复杂条件过滤 - 专家题

假设有一个复杂的对象结构,List<Department>,每个Department对象包含List<Team>,每个Team对象又包含List<Employee>。Employee对象有属性name(姓名)、age(年龄)、performance(绩效分数)。请使用Java Stream的filter方法,筛选出所有年龄大于40岁且绩效分数大于90分的员工所在的部门名称,并且以Set<String>形式返回部门名称集合,要求代码简洁高效,写出完整实现代码。
49.2万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.util.*;
import java.util.stream.Collectors;

class Employee {
    private String name;
    private int age;
    private int performance;

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

    public int getAge() {
        return age;
    }

    public int getPerformance() {
        return performance;
    }
}

class Team {
    private List<Employee> employees;

    public Team(List<Employee> employees) {
        this.employees = employees;
    }

    public List<Employee> getEmployees() {
        return employees;
    }
}

class Department {
    private String name;
    private List<Team> teams;

    public Department(String name, List<Team> teams) {
        this.name = name;
        this.teams = teams;
    }

    public String getName() {
        return name;
    }

    public List<Team> getTeams() {
        return teams;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Employee> employeeList1 = Arrays.asList(
                new Employee("Alice", 45, 95),
                new Employee("Bob", 35, 85)
        );
        List<Employee> employeeList2 = Arrays.asList(
                new Employee("Charlie", 42, 92),
                new Employee("David", 38, 88)
        );
        Team team1 = new Team(employeeList1);
        Team team2 = new Team(employeeList2);
        List<Team> teamList1 = Arrays.asList(team1);
        List<Team> teamList2 = Arrays.asList(team2);
        Department department1 = new Department("Department1", teamList1);
        Department department2 = new Department("Department2", teamList2);
        List<Department> departmentList = Arrays.asList(department1, department2);

        Set<String> result = departmentList.stream()
               .flatMap(department -> department.getTeams().stream())
               .flatMap(team -> team.getEmployees().stream())
               .filter(employee -> employee.getAge() > 40 && employee.getPerformance() > 90)
               .map(employee -> departmentList.stream()
                       .filter(department -> department.getTeams().stream()
                               .anyMatch(team -> team.getEmployees().contains(employee)))
                       .findFirst()
                       .map(Department::getName)
                       .orElse(null))
               .filter(Objects::nonNull)
               .collect(Collectors.toSet());

        System.out.println(result);
    }
}