Monday, June 10, 2013

Google guava "live" transformation - forcing an eager transformation

One of the utility classes provided by Google Guava Library, Lists, has a utility method to transform lists of one type to another. The interesting feature of this transformation is that the transformation is "live", in the sense that any changes to the source list is visible in the destination list. This is done by doing the transformation only on demand by applying a transformation on request.

This is best shown with an example:

Account a1 = new Account(1, "business", "num1");
Account a2 = new Account(2, "business", "num2");
Account a3 = new Account(3, "business", "num3");

List<Account> list = Lists.newArrayList(a1, a2, a3);

List<Integer> ids = Lists.transform(list, new Function<Account, Integer>() {
 @Override 
 public Integer apply(Account input) {
  return input.getId();
 }
});

assertThat(ids, contains(1, 2, 3));

a2.setId(12);
assertThat(ids, contains(1, 12, 3));


Here a list of "Account"(s) is being transformed to a list of its corresponding ids. Any change in the id of the original objects is reflected in the transformed list.

Now, there are situations where an eager transformation may be desired - for eg. needing to cache the transformed list, or serializing the transformed list. The way to force an eager transformation is to make a copy of the lazy list, using another utility method provided by the Lists class:

Lists.newArrayList(ids)

No comments:

Post a Comment