5.18. Using a Lazy Map

Problem

You need a Map that can populate a value when its corresponding key is requested.

Solution

Decorate a Map with LazyMap. Attempting to retrieve a value with a key that is not in a Map decorated with LazyMap will trigger the creation of a value by a Transformer associated with this LazyMap. The following example decorates a HashMap with a Transformer that reverses strings; when a key is requested, a value is created and put into the Map using this Transformer:

import java.util.*;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.map.LazyMap;
import org.apache.commons.lang.StringUtils;

// Create a Transformer to reverse strings - defined below
Transformer reverseString = new Transformer( ) {
    public Object transform( Object object ) {
        String name = (String) object;
        String reverse = StringUtils.reverse( name );
        return reverse;
    }
}

// Create a LazyMap called lazyNames, which uses the above Transformer
Map names = new HashMap( );
Map lazyNames = LazyMap.decorate( names, reverseString );

// Get and print two names
String name = (String) lazyNames.get( "Thomas" );
System.out.println( "Key: Thomas, Value: " + name );

name = (String) lazyNames.get( "Susan" );
System.out.println( "Key: Susan, Value: " + name );

Whenever get( ) is called, the decorated Map passes the requested key to a Transformer, and, in this case, a reversed string is put into a Map as a value. The previous example requests two strings and prints the following ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.