November 2004
Intermediate to advanced
400 pages
10h 31m
English
You need to perform logic that is predicated on a certain condition being satisfied, and you want to encapsulate this condition in an object.
Use a Predicate to evaluate a criteria or a
condition. A Predicate is an object that evaluates
another object and returns true or
false; predicates are used throughout the Commons
Collections packages for filtering, selecting, and validating the
contents of collections. This code demonstrates the use of simple
predicates to test the type and contents of an object:
import org.apache.commons.collection.Predicate; import org.apache.commons.collection.functors.*; String name = "Tim"; Predicate nameJohn = new EqualPredicate( "John" ); Predicate nameTim = new EqualPredicate( "Tim" ); Predicate instanceString = new InstanceofPredicate( String.class ); Predicate instanceDouble = new InstanceofPredicate( Double.class ); // Testing all predicates for "Tim" System.out.println( "Is Name John?: " + nameJohn.evaluate( name ) ); System.out.println( "Is Name Tim?: " + nameTim.evaluate( name ) ); System.out.println( "Is this a String?: " + instanceString.evaluate( name ) ); System.out.println( "Is this a Double?: " + instanceDouble.evaluate( name ) );
The previous example tests the name object against
a few Predicate implementations producing the
following console output:
Is Name John?: false Is Name Tim?: true Is this a String?: true Is this a Double?: false
The string “Tim” is subjected to
various Predicate tests. ...
Read now
Unlock full access