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" ...

Get Jakarta Commons Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.