commons-collections4-4.0-alpha1.jar包下的org.apache.commons.collections4.Predicate类,提供了部分自定义函数,可方便实现对容器的内容作出需要的判断。应用到实际项目中,可以极大的提高代码的可读性。
以下是代码示例:
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.PredicateUtils;
import org.apache.commons.collections4.functors.EqualPredicate;
import org.apache.commons.collections4.functors.NotNullPredicate;
import org.apache.commons.collections4.functors.UniquePredicate;
import org.apache.commons.collections4.list.PredicatedList;
//commons-collections4-4.0-alpha1.jar
public class PredicateDemo {
public static void main(String[] args) {
System.out.println("======自定义判断======");
//自定义的判别式:字符长度介于5~20之间
Predicate<String> selfPre = new Predicate<String>(){
@Override
public boolean evaluate(String object) {
return object.length()>=5 && object.length()<=20;
}};
Predicate notNull = NotNullPredicate.notNullPredicate();
//非空+字符长度介于5~20之间
Predicate all = PredicateUtils.allPredicate(notNull,selfPre);
List<String> list = PredicatedList.predicatedList(new ArrayList<String>(),all);
list.add("xxjsb");
list.add(null);//为空,抛出异常
list.add("bj");//长度不符,抛出异常
}
/**
* 判断唯一
*/
public static void unique(){
System.out.println("====唯一性判断====");
Predicate<Long> uniquePre = UniquePredicate.uniquePredicate();
List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(),uniquePre);
list.add(100L);
list.add(200L);
list.add(100L); //出现重复值,抛出异常
}
/**
* 判断非空
*/
public static void notNull(){
System.out.println("====非空判断====");
//Predicate notNull=NotNullPredicate.INSTANCE;
Predicate notNull = NotNullPredicate.notNullPredicate();
//String str ="bjs";
String str = null;
System.out.println(notNull.evaluate(str)); //如果非空为true ,否则为false
//添加容器值的判断
List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(),notNull);
list.add(1000L);
list.add(null); //验证失败,出现异常
}
/**
* 比较相等判断
*/
public static void equal(){
System.out.println("======相等判断======");
//Predicate<String> pre = new EqualPredicate<String>("xxjsb");
Predicate<String> pre = EqualPredicate.equalPredicate("xxjsb");
boolean flag = pre.evaluate("bj");
System.out.println(flag);
}
}