学习过Hibernate和Spring等童鞋,经常见到的一个回调机制。
如下:
package com.easyway.commons.ispace.dev.collection;
/**
* 对象比较的回调接口
* @author longgangbai
*
*/
public interface Predicate
{
public abstract boolean evaluate(Object obj);
}
下面是以下回调的方法:
/**
* 集合过滤的方法
* @param collection 过滤的集合
* @param predicate 过滤的条件
*/
@SuppressWarnings("unchecked")
public static void filter(Collection collection, Predicate predicate)
{
if(collection != null && predicate != null)
{
for(Iterator iterator = collection.iterator(); iterator.hasNext();)
{
Object obj = iterator.next();
if(!predicate.evaluate(obj))
iterator.remove();
}
}
}
@SuppressWarnings("unchecked")
public static Object find(Collection collection, Predicate predicate)
{
if(collection != null && predicate != null)
{
for(Iterator iterator = collection.iterator(); iterator.hasNext();)
{
Object obj = iterator.next();
if(predicate.evaluate(obj))
return obj;
}
}
return null;
}
/**
* 从集合中查询符合给定条件的对象集合
* @param collection 集合对象
* @param predicate 回调方法
* @return
*/
@SuppressWarnings("unchecked")
public static Collection select(Collection collection, Predicate predicate)
{
ArrayList arraylist = new ArrayList(collection.size());
select(collection, predicate, ((Collection) (arraylist)));
return arraylist;
}
/**
* 从集合中查询符合给定条件的对象集合
* @param collection 集合对象
* @param predicate 回调方法
* @param collection1 存储符合条件集合的Collection对象
*/
@SuppressWarnings("unchecked")
public static void select(Collection collection, Predicate predicate, Collection collection1)
{
if(collection != null && predicate != null)
{
for(Iterator iterator = collection.iterator(); iterator.hasNext();)
{
Object obj = iterator.next();
if(predicate.evaluate(obj))
collection1.add(obj);
}
}
}