Java BeanUtils - 篩選或過濾集合



說明

使用*Predicate* 介面可以篩選 bean 集合(由 commons-collections 提供),該介面根據輸入物件評估後返回 true 或 false 值。有一個名為 *BeanPropertyValueEqualsPredicate* 的謂詞,它會根據給定的值評估設定的屬性值。

語法

public BeanPropertyValueEqualsPredicate(String propertyName, Object propertyValue)

上述語法有兩個引數,用於確定要評估哪個屬性,以及屬性的預期值是什麼。它建立了一個 *Predicate*,用於評估目標物件,如果由 *propertyName* 指定的值等於由 *propertyValue* 指定的值,則返回 true;否則返回 false。

屬性名稱由 *org.apache.commons.beanutils.PropertyUtils* 定義,可以是簡單屬性、已編制索引屬性、巢狀屬性或對映屬性。

例如,您可以篩選一個 bean 集合,其中 myCar 屬性為 false

// create the closure
BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate( "myCar", Boolean.FALSE );
	
// filter the collection
CollectionUtils.filter( myCollection, predicate );

上述程式碼篩選了“myCollection”集合,並返回物件 myCar 屬性的布林值。

廣告
© . All rights reserved.