Java源码示例:org.apache.commons.collections4.PredicateUtils
示例1
@Override
public boolean evaluate(Object arg0) {
Predicate judgement = (Predicate) new NullPredicate();
if (predicates.size() == 1) {
judgement = predicates.get(0);
} else {
if (conj == Conjunction.AND) {
judgement = PredicateUtils.allPredicate(predicates);
}
else if (conj == Conjunction.OR) {
judgement = PredicateUtils.anyPredicate(predicates);
}
}
return judgement.evaluate(arg0);
}
示例2
/**
* Test find2.
*/
@Test
@SuppressWarnings("static-method")
public void testFind2(){
User guanyu30 = new User("关羽", 30);
List<User> list = toList(//
new User("张飞", 23),
new User("关羽", 24),
new User("刘备", 25),
guanyu30);
Predicate<User> predicate = PredicateUtils
.andPredicate(BeanPredicateUtil.equalPredicate("name", "关羽"), BeanPredicateUtil.equalPredicate("age", 30));
assertEquals(guanyu30, CollectionsUtil.find(list, predicate));
}
示例3
/**
* Test ignore case find 2.
*/
@Test
@SuppressWarnings("static-method")
public void testIgnoreCaseFind2(){
User guanyu30 = new User("guanYu", 30);
List<User> list = toList(//
new User("张飞", 23),
new User("guanyu1", 24),
new User("刘备", 25),
guanyu30);
Predicate<User> predicate = PredicateUtils.andPredicate(
BeanPredicateUtil.equalIgnoreCasePredicate("name", "guanyu"),
BeanPredicateUtil.equalPredicate("age", 30));
assertEquals(guanyu30, CollectionsUtil.find(list, predicate));
}
示例4
/**
* Test sum3.
*/
@Test
public void testSum3(){
User liubei = new User(10L);
liubei.setName("刘备");
liubei.setAge(50);
User guanyu = new User(20L);
liubei.setName("关羽");
guanyu.setAge(50);
User zhangfei = new User(100L);
zhangfei.setName("张飞");
zhangfei.setAge(null);
User zhaoyun = new User((Long) null);
zhaoyun.setName("赵云");
zhaoyun.setAge(100);
List<User> list = toList(liubei, guanyu, zhangfei, zhaoyun);
Predicate<User> notPredicate = PredicateUtils.notPredicate(BeanPredicateUtil.equalPredicate("name", "张飞"));
Map<String, BigDecimal> map = AggregateUtil.sum(list, toArray("id", "age"), notPredicate);
assertThat(map, allOf(hasEntry("id", toBigDecimal(30)), hasEntry("age", toBigDecimal(200))));
}
示例5
@Override
public boolean evaluate(Object arg0) {
Predicate judgement = (Predicate) new NullPredicate();
if (predicates.size() == 1) {
judgement = predicates.get(0);
} else {
if (conj == Conjunction.AND) {
judgement = PredicateUtils.allPredicate(predicates);
}
else if (conj == Conjunction.OR) {
judgement = PredicateUtils.anyPredicate(predicates);
}
}
return judgement.evaluate(arg0);
}
示例6
public boolean evaluate(Object arg0) {
Predicate judgement = new NullPredicate();
if (predicates.size() == 1) {
judgement = predicates.get(0);
} else {
if (conj == Conjunction.AND) {
judgement = PredicateUtils.allPredicate(predicates);
}
else if (conj == Conjunction.OR) {
judgement = PredicateUtils.anyPredicate(predicates);
}
}
return judgement.evaluate(arg0);
}
示例7
/**
* 获得 <code>klass</code> 排除某些 <code>excludeFieldNames</code> 之后的字段list.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>是所有字段的值(<b>不是属性</b>)</li>
* <li>自动过滤私有并且静态的字段,比如 LOGGER serialVersionUID</li>
* </ol>
* </blockquote>
*
* @param klass
* the klass
* @param excludeFieldNames
* 需要排除的field names,如果传递过来是null或者empty 那么不会判断
* @return 如果 <code>obj</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>excludeFieldNames</code> 是null或者empty,解析所有的field<br>
* 如果 {@link FieldUtils#getAllFieldsList(Class)} 是null或者empty,返回 {@link Collections#emptyList()}<br>
* 如果 <code>obj</code>没有字段或者字段都被参数 <code>excludeFieldNames</code> 排除掉了,返回 {@link Collections#emptyMap()}<br>
* @see FieldUtils#getAllFieldsList(Class)
* @since 1.7.1
*/
public static List<Field> getAllFieldList(final Class<?> klass,String...excludeFieldNames){
Validate.notNull(klass, "klass can't be null!");
//---------------------------------------------------------------
//获得给定类的所有声明字段 {@link Field},包括所有的parents,包括 public/protect/private/inherited...
List<Field> fieldList = FieldUtils.getAllFieldsList(klass);
if (isNullOrEmpty(fieldList)){
return emptyList();
}
//---------------------------------------------------------------
Predicate<Field> excludeFieldPredicate = BeanPredicateUtil.containsPredicate("name", excludeFieldNames);
Predicate<Field> staticPredicate = new Predicate<Field>(){
@Override
public boolean evaluate(Field field){
int modifiers = field.getModifiers();
// 私有并且静态 一般是log 或者 serialVersionUID
boolean isStatic = Modifier.isStatic(modifiers);
String pattern = "[{}.{}],modifiers:[{}]{}";
LOGGER.trace(pattern, klass.getSimpleName(), field.getName(), modifiers, isStatic ? " [isStatic]" : EMPTY);
return isStatic;
}
};
return selectRejected(fieldList, PredicateUtils.orPredicate(excludeFieldPredicate, staticPredicate));
}
示例8
@Test
public void testContainsPredicate12(){
User guanyu30 = new User("关羽", 30);
Predicate<User> predicate = PredicateUtils.andPredicate(
BeanPredicateUtil.containsPredicate("name", toList("关羽", "刘备")),
BeanPredicateUtil.containsPredicate("age", toList(30)));
assertEquals(true, predicate.evaluate(guanyu30));
}
示例9
@Test
public void testContainsPredicate12(){
User guanyu30 = new User("关羽", 30);
Predicate<User> predicate = PredicateUtils.andPredicate(
BeanPredicateUtil.containsPredicate("name", "关羽", "刘备"),
BeanPredicateUtil.containsPredicate("age", 30));
assertEquals(true, predicate.evaluate(guanyu30));
}
示例10
/**
* Test.
*/
@Test
public void test(){
User user = new User("feilong");
Predicate<User> predicate = new BeanPredicate<>("name", PredicateUtils.equalPredicate("feilong"));
assertTrue(predicate.evaluate(user));
}
示例11
/**
* Test sum 3111.
*/
@Test
public void testSum3111(){
User zhangfei = new User(100L);
zhangfei.setName("张飞");
zhangfei.setAge(null);
List<User> list = toList(zhangfei);
Predicate<User> notPredicate = PredicateUtils.notPredicate(BeanPredicateUtil.equalPredicate("name", "张飞"));
Map<String, BigDecimal> map = AggregateUtil.sum(list, toArray("id", "age"), notPredicate);
assertEquals(true, isNullOrEmpty(map));
}
示例12
private FilterPredicate(@NonNull Settings settings, @NonNull Set<WiFiBand> wiFiBands) {
Predicate<WiFiDetail> ssidPredicate = makeSSIDPredicate(settings.getSSIDs());
Predicate<WiFiDetail> wiFiBandPredicate = EnumUtils.predicate(WiFiBand.class, wiFiBands, new WiFiBandTransformer());
Predicate<WiFiDetail> strengthPredicate = EnumUtils.predicate(Strength.class, settings.getStrengths(), new StrengthTransformer());
Predicate<WiFiDetail> securityPredicate = EnumUtils.predicate(Security.class, settings.getSecurities(), new SecurityTransformer());
List<Predicate<WiFiDetail>> predicates = Arrays.asList(ssidPredicate, wiFiBandPredicate, strengthPredicate, securityPredicate);
this.predicate = PredicateUtils.allPredicate(CollectionUtils.select(predicates, new NoTruePredicate()));
}
示例13
@NonNull
private Predicate<WiFiDetail> makeSSIDPredicate(Set<String> ssids) {
if (ssids.isEmpty()) {
return PredicateUtils.truePredicate();
}
return PredicateUtils.anyPredicate(CollectionUtils.collect(ssids, new SSIDTransformer()));
}
示例14
@NonNull
@Override
public List<String> findVendors(@NonNull String filter) {
if (StringUtils.isBlank(filter)) {
return new ArrayList<>(getVendors().keySet());
}
Locale locale = Locale.getDefault();
String filterToUpperCase = filter.toUpperCase(locale);
List<Predicate<String>> predicates = Arrays.asList(new StringContains(filterToUpperCase), new MacContains(filterToUpperCase));
return new ArrayList<>(CollectionUtils.select(getVendors().keySet(), PredicateUtils.anyPredicate(predicates)));
}
示例15
@NonNull
public static <T extends Enum, U> Predicate<U> predicate(@NonNull Class<T> enumType, @NonNull Collection<T> input, @NonNull Transformer<T, Predicate<U>> transformer) {
if (input.size() >= values(enumType).size()) {
return PredicateUtils.truePredicate();
}
return PredicateUtils.anyPredicate(CollectionUtils.collect(input, transformer));
}
示例16
@Test
public void testFindUsingPredicate() {
// setup
final TestObject expected = TestObject.VALUE3;
Predicate<TestObject> predicate = PredicateUtils.equalPredicate(expected);
// execute
TestObject actual = EnumUtils.find(TestObject.class, predicate, TestObject.VALUE2);
// validate
assertEquals(expected, actual);
}
示例17
@Test
public void testFindUsingPredicateWhenNothingFound() {
// setup
TestObject expected = TestObject.VALUE2;
Predicate<TestObject> predicate = PredicateUtils.falsePredicate();
// execute
TestObject actual = EnumUtils.find(TestObject.class, predicate, expected);
// validate
assertEquals(expected, actual);
}
示例18
public boolean evaluate(Object arg0) {
Predicate judgement = new NullPredicate();
if (predicates.size() == 1) {
judgement = predicates.get(0);
} else {
if (conj == Conjunction.AND) {
judgement = PredicateUtils.allPredicate(predicates);
}
else if (conj == Conjunction.OR) {
judgement = PredicateUtils.anyPredicate(predicates);
}
}
return judgement.evaluate(arg0);
}
示例19
@Test
public final void givenListContainsNulls_whenRemovingNullsWithCommonsCollections_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
assertThat(list, hasSize(3));
}
示例20
@Override
public SiteItem getSiteItem(String url, ItemProcessor processor, Predicate<Item> predicate) {
SiteContext context = getSiteContext();
if(!storeService.exists(context.getContext(), url)) {
return null;
}
if (CollectionUtils.isNotEmpty(defaultPredicates)) {
List<Predicate<Item>> predicates = new ArrayList<>(defaultPredicates);
if (predicate != null) {
predicates.add(predicate);
}
predicate = PredicateUtils.allPredicate(predicates);
}
if (CollectionUtils.isNotEmpty(defaultProcessors)) {
ItemProcessorPipeline processorPipeline = new ItemProcessorPipeline(new ArrayList<>(defaultProcessors));
if (processor != null) {
processorPipeline.addProcessor(processor);
}
processor = processorPipeline;
}
Item item = storeService.findItem(context.getContext(), null, url, processor);
if (item != null && (predicate == null || predicate.evaluate(item))) {
return createItemWrapper(item);
} else {
return null;
}
}
示例21
@Override
public List<Workflow> getDependentWorkflows(@VelocityCheck int companyId, Collection<WorkflowDependency> dependencies, boolean exceptInactive) {
final Set<WorkflowDependency> filteredDependencies = new HashSet<>(CollectionUtils.emptyIfNull(dependencies));
CollectionUtils.filter(filteredDependencies, PredicateUtils.notNullPredicate());
if (companyId <= 0 || filteredDependencies.isEmpty()) {
return Collections.emptyList();
}
StringBuilder sqlBuilder = new StringBuilder();
List<Object> sqlParameters = new ArrayList<>();
sqlBuilder.append("SELECT w.* FROM workflow_tbl w ")
.append("JOIN workflow_dependency_tbl dep ON dep.workflow_id = w.workflow_id AND dep.company_id = w.company_id ")
.append("WHERE w.company_id = ? ");
sqlParameters.add(companyId);
sqlBuilder.append("AND ( ");
boolean isFirstDependency = true;
for(WorkflowDependency dependency : filteredDependencies) {
if(!isFirstDependency){
sqlBuilder.append(" OR");
}
isFirstDependency = false;
sqlBuilder.append("(dep.type = ? ");
sqlParameters.add(dependency.getType().getId());
if (dependency.getEntityId() > 0) {
sqlBuilder.append("AND dep.entity_id = ? ");
sqlParameters.add(dependency.getEntityId());
} else {
sqlBuilder.append("AND dep.entity_name = ? ");
sqlParameters.add(dependency.getEntityName());
}
sqlBuilder.append(" )");
}
sqlBuilder.append(" )");
if (exceptInactive) {
sqlBuilder.append("AND w.status IN (?, ?) ");
sqlParameters.add(WorkflowStatus.STATUS_ACTIVE.getId());
sqlParameters.add(WorkflowStatus.STATUS_TESTING.getId());
}
sqlBuilder.append("ORDER BY w.workflow_id DESC");
return select(logger, sqlBuilder.toString(), new WorkflowRowMapper(), sqlParameters.toArray());
}
示例22
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response){
final SlingScriptHelper sling = getScriptHelper(request);
final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
final Config dsCfg = new Config(request.getResource().getChild(Config.DATASOURCE));
final CommerceBasePathsService cbps = sling.getService(CommerceBasePathsService.class);
final String query = ex.getString(dsCfg.get("query", String.class));
final String parentPath;
final String searchName;
final String rootPath = ex.getString(dsCfg.get("rootPath", cbps.getProductsBasePath()));
if (query != null) {
final int slashIndex = query.lastIndexOf('/');
if (slashIndex < 0) {
parentPath = rootPath;
searchName = query.toLowerCase();
} else if (!query.startsWith(rootPath)) {
parentPath = rootPath;
searchName = null;
} else if (slashIndex == query.length() - 1) {
parentPath = query;
searchName = null;
} else {
parentPath = query.substring(0, slashIndex + 1);
searchName = query.substring(slashIndex + 1).toLowerCase();
}
} else {
parentPath = ex.getString(dsCfg.get("path", String.class));
searchName = null;
}
final Resource parent = request.getResourceResolver().getResource(parentPath);
final DataSource ds;
if (parent == null) {
ds = EmptyDataSource.instance();
} else {
final Integer offset = ex.get(dsCfg.get("offset", String.class), Integer.class);
final Integer limit = ex.get(dsCfg.get("limit", String.class), Integer.class);
final String itemRT = dsCfg.get("itemResourceType", String.class);
final String filter = ex.getString(dsCfg.get("filter", String.class));
final Collection<Predicate<Resource>> predicates = new ArrayList<>(2);
predicates.add(createPredicate(filter));
if (searchName != null) {
final Pattern searchNamePattern = Pattern.compile(Pattern.quote(searchName), Pattern.CASE_INSENSITIVE);
predicates.add(resource -> searchNamePattern.matcher(resource.getName()).lookingAt());
}
final Predicate predicate = PredicateUtils.allPredicate(predicates);
final Transformer transformer = createTransformer(itemRT, predicate);
final List<Resource> list;
if (FILTER_CATEGORY.equals(filter)) {
class CategoryFinder extends AbstractResourceVisitor {
private CategoryPredicate categoryPredicate = new CategoryPredicate();
private List<Resource> categories = new ArrayList<Resource>();
@Override
protected void visit(Resource res) {
if (categoryPredicate.evaluate(res)) {
categories.add(res);
}
}
};
CategoryFinder categoryFinder = new CategoryFinder();
categoryFinder.accept(parent);
list = IteratorUtils.toList(new FilterIterator(categoryFinder.categories.iterator(), predicate));
} else {
list =IteratorUtils.toList(new FilterIterator(parent.listChildren(), predicate));
}
//force reloading the children of the root node to hit the virtual resource provider
if (rootPath.equals(parentPath)) {
for (int i = 0; i < list.size(); i++) {
list.set(i, request.getResourceResolver().getResource(list.get(i).getPath()));
}
}
@SuppressWarnings("unchecked")
DataSource datasource = new AbstractDataSource() {
public Iterator<Resource> iterator() {
Collections.sort(list, Comparator.comparing(Resource::getName));
return new TransformIterator(new PagingIterator<>(list.iterator(), offset, limit), transformer);
}
};
ds = datasource;
}
request.setAttribute(DataSource.class.getName(), ds);
}
示例23
/**
* Sync builds with dashboards
*
* @param build
*/
public void sync(Build build) {
/* Step 1: Add build collector item to Dashboard if built repo is in on the dashboard. */
// Find the collectorItem of build
CollectorItem buildCollectorItem = collectorItemRepository.findOne(build.getCollectorItemId());
//Find possible collectors and then the collector ids for SCM
List<Collector> scmCollectors = collectorRepository.findAllByCollectorType(CollectorType.SCM);
if (CollectionUtils.isEmpty(scmCollectors)) {
return;
}
List<ObjectId> scmCollectorIds = scmCollectors.stream().map(BaseModel::getId).collect(Collectors.toList());
// Get the repos that are being built
List<RepoBranch> repos = build.getCodeRepos();
Set<CollectorItem> repoCollectorItemsInBuild = new HashSet<>();
//create a list of the repo collector items that are being built, most cases have only 1
if (CollectionUtils.isEmpty(repos)) return;
CollectionUtils.filter(repos, PredicateUtils.notNullPredicate());
repos.forEach((
repoBranch -> {
Map<String, Object> options = new HashMap<>();
options.put("url", repoBranch.getUrl());
if (StringUtils.isNotEmpty(repoBranch.getBranch())) {
options.put("branch", repoBranch.getBranch());
}
repoCollectorItemsInBuild.addAll(IterableUtils.toList(collectorItemRepository.findAllByOptionMapAndCollectorIdsIn(options, scmCollectorIds)));
}));
repoCollectorItemsInBuild.forEach(rci->{
rci.setEnabled(true);
collectorItemRepository.save(rci);
});
// For each repo collector item, add the item to the referenced dashboards
repoCollectorItemsInBuild.forEach(
ci -> relatedCollectorItemRepository.saveRelatedItems(buildCollectorItem.getId(), ci.getId(), this.getClass().toString(), Reason.BUILD_REPO_REASON.getAction())
);
}
示例24
/**
* 用来判断一个对象指定的属性以及属性值是否相等.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 在list中查找 名字是 关羽,并且 年龄是30 的user
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* Predicate{@code <User>} predicate = PredicateUtils
* .andPredicate(BeanPredicateUtil.equalPredicate("name", "关羽"), BeanPredicateUtil.equalPredicate("age", 30));
*
* assertEquals(guanyu30, CollectionsUtil.find(list, predicate));
* </pre>
*
* <p>
* 此时你可以优化成:
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* Map{@code <String, Object>} map = ConvertUtil.toMap("name", "关羽", "age", 30);
* assertEquals(guanyu30, find(list, BeanPredicateUtil.{@code <User>} equalPredicate(map)));
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param propertyNameAndPropertyValueMap
* 属性和指定属性值对应的map,其中key是泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @return 如果 <code>propertyNameAndPropertyValueMap</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyNameAndPropertyValueMap</code> 是empty,抛出{@link IllegalArgumentException}<br>
* 如果 <code>propertyNameAndPropertyValueMap</code> 中有key是null,抛出{@link NullPointerException}<br>
* 如果 <code>propertyNameAndPropertyValueMap</code> 中有key是blank,抛出{@link IllegalArgumentException}<br>
* @see #equalPredicate(String, Object)
* @since 1.9.5
*/
public static <T> Predicate<T> equalPredicate(Map<String, ?> propertyNameAndPropertyValueMap){
Validate.notEmpty(propertyNameAndPropertyValueMap, "propertyNameAndPropertyValueMap can't be null!");
@SuppressWarnings("unchecked")
BeanPredicate<T>[] beanPredicates = ArrayUtil.newArray(BeanPredicate.class, propertyNameAndPropertyValueMap.size());
int index = 0;
for (Map.Entry<String, ?> entry : propertyNameAndPropertyValueMap.entrySet()){
String propertyName = entry.getKey();
Object propertyValue = entry.getValue();
Validate.notBlank(propertyName, "propertyName can't be blank!");
Array.set(beanPredicates, index, equalPredicate(propertyName, propertyValue));
index++;
}
return PredicateUtils.allPredicate(beanPredicates);
}
示例25
@Test
@SuppressWarnings("static-method")
public void testEqualPredicateNullMap(){
assertEquals(PredicateUtils.nullPredicate(), BeanPredicateUtil.equalPredicate((User) null));
}
示例26
@Override
public boolean evaluate(Predicate<WiFiDetail> object) {
return !PredicateUtils.truePredicate().equals(object);
}
示例27
@Override
public Predicate<TestObject> transform(TestObject input) {
return PredicateUtils.truePredicate();
}
示例28
@Test(expected = IllegalArgumentException.class)
public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() {
Map<String, String> uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
uniqValuesMap.put("NEW_RED", "#FF0000");
}
示例29
/**
* 构造属性与一个指定对象 <code>bean</code> 的一组属性的值 <code>propertyNames</code> 都相等的判断器.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 在list中查找 名字是 关羽,并且 年龄是30 的user
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* Predicate{@code <User>} predicate = PredicateUtils
* .andPredicate(BeanPredicateUtil.equalPredicate("name", "关羽"), BeanPredicateUtil.equalPredicate("age", 30));
*
* assertEquals(guanyu30, CollectionsUtil.find(list, predicate));
* </pre>
*
* <p>
* 此时你可以优化成:
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* assertEquals(guanyu30, find(list, BeanPredicateUtil.equalPredicate(guanyu30, "name", "age")));
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param bean
* the bean
* @param propertyNames
* 如果 <code>propertyNames</code> 是null或者empty 那么取所有属性值.
* @return 如果 <code>bean</code> 是null,返回 {@link org.apache.commons.collections4.PredicateUtils#nullPredicate()}<br>
* 否则 调用 {@link com.feilong.core.bean.PropertyUtil#describe(Object, String...)} 提取属性值,再调用 {@link #equalPredicate(Map)}
* @see #equalPredicate(String, Object)
* @see com.feilong.core.bean.PropertyUtil#describe(Object, String...)
* @since 1.10.6
*/
public static <T> Predicate<T> equalPredicate(T bean,String...propertyNames){
if (null == bean){
return PredicateUtils.nullPredicate();
}
Map<String, ?> propertyNameAndPropertyValueMap = PropertyUtil.describe(bean, propertyNames);
return equalPredicate(propertyNameAndPropertyValueMap);
}
示例30
/**
* 用来指定 <code>T</code> 对象的特定属性 <code>propertyName</code> equals 指定的 <code>propertyValue</code>.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 在list中查找 名字是 关羽,并且 年龄是30 的user
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* Predicate{@code <User>} predicate = PredicateUtils
* .andPredicate(BeanPredicateUtil.equalPredicate("name", "关羽"), BeanPredicateUtil.equalPredicate("age", 30));
*
* assertEquals(guanyu30, CollectionsUtil.find(list, predicate));
*
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param <V>
* the value type
* @param propertyName
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @param propertyValue
* the property value
* @return 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* @see org.apache.commons.collections4.PredicateUtils#equalPredicate(Object)
*/
public static <T, V> Predicate<T> equalPredicate(String propertyName,V propertyValue){
Validate.notBlank(propertyName, "propertyName can't be blank!");
return new BeanPredicate<>(propertyName, PredicateUtils.equalPredicate(propertyValue));
}