LazyMap.decorate()和ChainedTransformer的用处

import java.util.*;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.map.LazyMap;
import org.apache.commons.lang.StringUtils;
public class LazyMapTest {
public static void main(String[]args){
// Create a Transformer to reverse strings - defined below

final 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 );//将Map和transformer传递给lazymap
// Get and print two names
String name = (String) lazyNames.get("Thomas");//调用LazyMap里面的get()方法如果,没有这个key会调用transform方法获得value,返回get
System.out.println("name:"+name);
}

}


###使用transformer chain

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

public class LazyMapTest {

public static void main(String[]args){
	
	// Create a Transformer to reverse strings - defined below
	final Transformer reverseString = new Transformer( ) {
		
	    public Object transform( Object object ) {
	    	
	            
	        Long number = (Long) object;
	        
	         return( new Long( number.longValue() * 100 ) );
	    }
	};
	
	Transformer increment = new Transformer( ) {
	    public Object transform(Object input) {
	                Long number = (Long) input;
	         return( new Long( number.longValue( ) + 1 ) );
	        }
	};
	
	Transformer[] chainElements = new Transformer[] { reverseString , increment };//一个transformer 结果作为另外一个transform的输入值
	
	Transformer chain = new ChainedTransformer( chainElements );

	Long original = new Long( 34 );
	
	Long result = (Long) chain.transform(original);

	System.out.println( "Original: " + original );
	
	System.out.println( "Result: " + result );
	// Create a LazyMap called lazyNames, which uses the above Transformer
	
	
	}
	
}

转载于:https://my.oschina.net/u/2308739/blog/618976

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值