Sunday, July 4, 2010

Iterable transformations using Guava

I love Groovy for spread operator (for example users*.name). Google Guava allows you to do the same using the Function interface and Iterables.transform() method.

Function<Date, Integer> YEAR = new Function<Date, Integer>() {

  public Integer apply(Date date) {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.YEAR);


Date[] dates = {new Date(), new Date(), new Date()};
Iterable<Integer> yearsIterable = Iterables.transform(Lists.newArrayList(dates), YEAR);
List<Integer> years = Lists.newArrayList(yearsIterable);


No comments:

Post a Comment