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

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