Guava-Functional Programming with Guava

Using the Functions class

Functions.forMap

The forMap method takes Map<K,V> and returns a function (Function<K,V>) whose apply method will perform a map lookup. For example, consider the following class representing a state in the United States:

public class State {
       private String name;
       private String code;
       private Set<City> mainCities = new HashSet<City>();
}

Now consider that you have a map named stateMap in the form of Map<String,State> where the string key would be the state abbreviation. Now to create the function that would perform the lookup by state code, you would simply do the following:

   Function<String,State> lookup = Functions.forMap(stateMap);
   //Would return State object for NewYork
   lookup.apply("NY");

There is one caveat to using the Functions.forMap method. The map returned by Functions.forMap will throw an IllegalArgumentException exception if the given key is not found in the map. However, there is another version of Functions. forMap that takes an additional parameter to be used as a default value, should the given key not be found in the map. By using a Function interface to perform the state lookups, you can easily change out the implementation. When combining it with a Splitter object to create a map or when using some of the other methods for map creation in the Guava collection package, we are leveraging the power of Guava in our code.

Using the Functions.compose method

假设你有另外一个表示city的类。它的定义如下:

public class City {
       private String name;
       private String zipCode;
       private int population;
       public String toString() {
        return name;
} }

考虑一下这个场景:你需要创建一个Function实例。这个实例能够将一个给定的State对象转换为该State包含的主要城市并以逗号分隔的字符串。Function类的定义应该像下面这个样子:

public class StateToCityString implements Function<State,String> {
       @Override
       public String apply(State input) {
           return Joiner.on(",").join(input.getMainCities());
       }
}

更进一步,如果你想要一个单独的Function实例完成State的缩写到到由State包含主要城市组装并以逗号分隔的字符串转换。这时候Functions.compose方法能够帮助完成这项工作。

Function<String,State> lookup = Functions.forMap(stateMap);
Function<State, String> stateFunction = new StateToCityString();
Function<String,String> composed = Functions.compose(stateFunction ,lookup);
composed.apply("NY");//输出"Albany,Buffalo,NewYorkCity"
//等同于上面的操作。注意上面两个function的参数顺序
String cities = stateFunction.apply(lookup.apply("NY"));

Using the Predicates class

  • Predicates.and
  • Predicates.or
  • Predicates.not
  • Predicates.compose(Predicate p,Function f)

Using the Suppliers class

  • Suppliers.memoize
    The Suppliers.memoize method returns a Supplier instance that wraps a provided delegate Supplier instance. When the first call to get is executed, the call is passed to the delegate Supplier instance; it creates and returns the instance to the wrapping Supplier object. The wrapping Supplier object caches the instance before returning it to the caller. All subsequent calls to the get method return the cached instance. Here’s how we
    could use Suppliers.memoize:
Supplier<Predicate<String>> wrapped = Suppliers.memoize(composedPredicateSupplier);

By adding just one line of code, we can now return the same instance of the Predicate object with each call to the Supplier object.

  • Suppliers.memoizeWithExpiration
    The Suppliers.memoizeWithExpiration method works in the exact same manner as its memoize brother with the exception that after a given period of time when get is called, the wrapper Supplier object retrieves the instance from the delegate Supplier. object The wrapper Supplier instance then caches the instance for the given period of time. Take note that the instance is not held in a physical cache; rather the wrapping Supplier object keeps an instance variable that is set to the value returned by the delegate Supplier object. Here’s an example:
Supplier<Predicate<String>> wrapped = Suppliers.memoize(composedPredicateSupplier,10L,TimeUnit.MINUTES);

Here we’ve wrapped Supplier again and set the timeout to be 10 minutes.
For ComposedPredicateSupplier, it won’t make much difference; but for Supplier that is returning an object that could have changes, something retrieved from a database, for example, the memoizeWithExpiration method, could be very helpful.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值