java怎么从list中查找匹配属性

2024-04-24

要从一个List中查找匹配属性的对象,可以使用Java Stream API中的filter方法结合Lambda表达式来实现。以下是一个示例代码:

假设有一个名为Person的类,其中有一个属性名为name:

public class Person {
    private String name;

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

    public String getName() {
        return name;
    }
}

现在有一个List列表,我们想要从中查找name属性为"John"的Person对象:

List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice"));
personList.add(new Person("Bob"));
personList.add(new Person("John"));
personList.add(new Person("Mary"));

Person result = personList.stream()
    .filter(person -> person.getName().equals("John"))
    .findFirst()
    .orElse(null);

if (result != null) {
    System.out.println("Found person with name John: " + result.getName());
} else {
    System.out.println("Person with name John not found");
}

在上面的代码中,我们使用了Stream的filter方法来筛选符合条件的对象,Lambda表达式person -> person.getName().equals("John")用来判断是否name属性等于"John"。然后我们使用findFirst方法来获取第一个匹配的对象,如果没有找到,则返回null。最后我们输出找到的结果或者未找到的提示信息。