MST
星途 面试题库

面试题:Java中Stream flatMap在复杂对象结构下的一对多转换应用

假设有一个类`Department`,它有一个属性是`List<Employee>`,代表该部门的员工列表。`Employee`类有属性`name`(姓名)和`skills`(技能列表,类型为`List<String>`)。现在有一个`List<Department>`,请使用Stream的flatMap方法,获取所有员工的所有技能组成的一个单一的流,并统计不同技能的数量。请写出完整的Java代码实现。
50.1万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

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

class Employee {
    private String name;
    private List<String> skills;

    public Employee(String name, List<String> skills) {
        this.name = name;
        this.skills = skills;
    }

    public List<String> getSkills() {
        return skills;
    }
}

class Department {
    private List<Employee> employees;

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

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

public class Main {
    public static void main(String[] args) {
        List<Employee> emp1List = Arrays.asList(new Employee("Alice", Arrays.asList("Java", "Python")),
                new Employee("Bob", Arrays.asList("C++", "Java")));
        List<Employee> emp2List = Arrays.asList(new Employee("Charlie", Arrays.asList("Python", "JavaScript")));
        List<Department> departments = Arrays.asList(new Department(emp1List), new Department(emp2List));

        long distinctSkillCount = departments.stream()
               .flatMap(department -> department.getEmployees().stream())
               .flatMap(employee -> employee.getSkills().stream())
               .distinct()
               .count();

        System.out.println("不同技能的数量: " + distinctSkillCount);
    }
}