November 2004
Intermediate to advanced
400 pages
10h 31m
English
You need to ensure that all
values added to a
Map satisfy a set of arbitrary conditions.
Decorate an existing Map with
PredicatedMap
from Commons Collections. Predicates add an
inbound validation to a Map, validating keys or
values any time an entry is added to a
PredicatedMap. If a Predicate
assigned to a key or value returns
false, put()
throws an IllegalArgumentException. The following
example decorates a HashMap with
PredicatedMap—two
Predicates are created to validate the keys and
the values:
import java.util.*; import org.apache.commons.collections.map.PredicatedMap; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.functors.EqualPredicate; import org.apache.commons.collections.functors.InstanceofPredicate; import org.apache.commons.collections.functors.OrPredicate;// Create a Predicate that only accepts StringsPredicate onlyStrings = new InstanceofPredicate( String.class );// Create a Predicate that only allows "green" or "red" Predicate onlyGreen = new EqualPredicate( "green" ); Predicate onlyRed = new EqualPredicate( "red" ); Predicate greenOrRed = new OrPredicate( onlyGreen, onlyRed );// Created a Decorated Map - accepting String keys and "green" or "red" valuesMap map = PredicatedMap.decorate( new HashMap( ), onlyStrings, greenOrRed );// All of these puts should work map.put( "tony" , "green" ); map.put( "alice" , "red" ); map.put( "mike" , "red" ); map.put( "bobby" , "green" ...
Read now
Unlock full access