按内部对象字段查询
创始人
2024-11-03 12:31:52
0

以下是一个示例代码,演示了如何按内部对象字段进行查询。

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class Employee {
    private String name;
    private int age;
    private Department department;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Department getDepartment() {
        return department;
    }
}

class Department {
    private String name;

    public Department(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        List employees = new ArrayList<>();
        employees.add(new Employee("John", 30, new Department("HR")));
        employees.add(new Employee("Jane", 35, new Department("Finance")));
        employees.add(new Employee("Michael", 25, new Department("HR")));
        employees.add(new Employee("Emily", 28, new Department("IT")));

        String departmentNameToSearch = "HR";

        List filteredEmployees = employees.stream()
                .filter(employee -> employee.getDepartment().getName().equals(departmentNameToSearch))
                .collect(Collectors.toList());

        for (Employee employee : filteredEmployees) {
            System.out.println("Name: " + employee.getName() + ", Age: " + employee.getAge());
        }
    }
}

在上面的示例中,我们创建了一个Employee类和一个Department类。Employee类有一个Department对象作为其字段之一。我们创建了一个包含多个Employee对象的列表。

然后,我们定义了一个departmentNameToSearch变量,用于指定要搜索的部门名称。

使用Java 8的流(Stream)API,我们可以通过过滤employees列表来查找具有特定部门名称的员工。在过滤条件中,我们使用employee.getDepartment().getName().equals(departmentNameToSearch)来比较Employee对象的department字段的名称与departmentNameToSearch变量的值是否相等。最后,我们使用collect(Collectors.toList())将过滤后的结果收集到一个新的列表中。

最后,我们遍历过滤后的员工列表,并打印每个员工的名称和年龄。

在实际应用中,您可以根据需要自定义过滤条件和操作。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...