溫馨提示×

java怎么從list中查找匹配屬性

小億
385
2024-04-01 19:23:59
欄目: 編程語言

要從一個List中查找匹配屬性的對象,可以使用Java Stream API中的filter方法結(jié)合Lambda表達(dá)式來實現(xiàn)。以下是一個示例代碼:

假設(shè)有一個名為Person的類,其中有一個屬性名為name:

public class Person {
    private String name;

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

    public String getName() {
        return name;
    }
}

現(xiàn)在有一個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表達(dá)式person -> person.getName().equals("John")用來判斷是否name屬性等于"John"。然后我們使用findFirst方法來獲取第一個匹配的對象,如果沒有找到,則返回null。最后我們輸出找到的結(jié)果或者未找到的提示信息。

0