O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.14. Constraining Map Values

Problem

You need to ensure that all values added to a Map satisfy a set of arbitrary conditions.

Solution

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 Strings
               Predicate 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" values
               Map 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" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required