共計 866 個字符,預計需要花費 3 分鐘才能閱讀完成。
要從一個 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。最后我們輸出找到的結果或者未找到的提示信息。
丸趣 TV 網 – 提供最優質的資源集合!
正文完